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 LikeButton from './components/LikeButton.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 smoothscroll from 'smoothscroll-polyfill';
import { useCssVar } from '@vueuse/core';
import { watch, watchEffect, computed } from 'vue';
import { Capacitor } from '@capacitor/core';
import { StatusBar, Style } from '@capacitor/status-bar';
import { SplashScreen } from '@capacitor/splash-screen';
import { SafeArea } from '@aashu-dubey/capacitor-statusbar-safe-area';
require('dayjs/locale/zh-cn');

window.isNativePlatform = Capacitor.isNativePlatform();

smoothscroll.polyfill();
const appHeight = useCssVar('--app-height', document.documentElement);
const onWindowResize = () => {
    if (window.isNativePlatform) {
        appHeight.value = `${window.screen.height}px`;
    } else {
        appHeight.value = `${window.innerHeight}px`;
    }
};
window.addEventListener('resize', onWindowResize);
onWindowResize();
setTimeout(() => {
    onWindowResize();
}, 100);

Toast.setDefaultOptions('loading', { duration: 0 });
Dialog.setDefaultOptions({ theme: 'round-button' });

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('setShowConsole', true);
}
store.commit('setFirstUrl', location.href);

import PullRefresh from './components/PullRefresh.vue';
import { setTimeout } from 'core-js';
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 emitter = mitt();
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('like-button', LikeButton)
    .component('van-pull-refresh', PullRefresh)
    .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);
app.config.unwrapInjectedRef = true;
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);
    }
}
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);
}

store.commit('setPlatform', /iPad|iPhone|iPod/i.test(navigator.userAgent) ? 'ios' : 'android');

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 = () => {
            console.log('splash onload');
            onload && onload();
            setTimeout(() => {
                hideSplash();
            }, 2000);
        };
        splash.onerror = () => {
            hideSplash();
            onerror && onerror();
        };
        setTimeout(() => {
            hideSplash();
        }, 5000);
        splash.src = 'https://cdn.raex.vip/image/2022-08-10-14-42-48HbJaApDQ.jpg';
        document.body.append(splash);
    });
if (navigator.userAgent.includes('#review#')) {
    store.commit('setReview', true);
}
if (window.isNativePlatform) {
    store.commit('setPlatform', Capacitor.getPlatform());
    document.addEventListener(
        'deviceready',
        function () {
            StatusBar.setOverlaysWebView({ overlay: true });
            function mountApp() {
                window.$vm = app.mount('#app');
            }
            loadSplash(
                () => {
                    setTimeout(() => {
                        SplashScreen.hide();
                    }, 100);
                    mountApp();
                },
                () => {
                    SplashScreen.hide();
                    mountApp();
                }
            ).then(res => {
                StatusBar.setStyle({ style: Style.Light });
            });
            calcSafeArea();
            window.StatusBar = StatusBar;
            if ('android' === Capacitor.getPlatform()) {
                SafeArea.getSafeAreaInsets().then(res => {
                    console.log('safeArea', res);
                    safeTop.value = res.top + 'px';
                    safeRight.value = res.right + 'px';
                    safeBottom.value = res.bottom + 'px';
                    safeLeft.value = res.left + 'px';
                    StatusBar.setStyle({ style: Style.Light });
                });
            } 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
            );
        },
        false
    );
} else {
    loadSplash().then(res => {
        window.$vm = app.mount('#app');
        calcSafeArea();
    });
    calcSafeArea();
}
