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 } from 'vant';

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 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);
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);
}
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://cdn.raex.vip/splash.jpg?ts=' + new Date().getTime();
        document.body.append(splash);
    });
if (navigator.userAgent.includes('#cordova#')) {
    document.addEventListener(
        'deviceready',
        function () {
            StatusBar.overlaysWebView(true);
            window.$vm = app.mount('#app');
            loadSplash(
                () => {
                    setTimeout(() => {
                        navigator.splashscreen.hide();
                    }, 100);
                },
                () => {
                    navigator.splashscreen.hide();
                }
            ).then(res => {
                StatusBar.overlaysWebView(false);
                StatusBar.backgroundColorByHexString('#F5F7FA');
                StatusBar.styleDefault();
            });

            if (/iphone|ipad|ipod/i.test(navigator.userAgent)) {
                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)');
            } else {
                if (window.AndroidNotch) {
                    window.AndroidNotch.getInsetTop(
                        px => {
                            style.setProperty('--safe-top', px + 'px');
                        },
                        err => console.error('Failed to get insets top:', err)
                    );

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

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

                    window.AndroidNotch.getInsetLeft(
                        px => {
                            style.setProperty('--safe-left', px + 'px');
                        },
                        err => console.error('Failed to get insets left:', err)
                    );
                }
            }

            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 (!(/.+\.raex\.vip/.test(location.host) || /192\.168/.test(location.host))) {
                if (!/iphone|ipad|ipod|Macintosh/i.test(navigator.userAgent)) {
                    window.$vm.$dialog.alert({
                        message: '检测到新版本，请下载更新',
                        confirmButtonText: '下载更新',
                        beforeClose(action, done) {
                            console.log(action);
                            if (/iphone|ipad|ipod|Macintosh/i.test(navigator.userAgent)) {
                                //location.href = 'https://apps.apple.com/cn/app/id1598469798';
                            } else {
                                location.href = 'http://download.raex.vip';
                            }
                        }
                    });
                }
            }

            if (window.store && /iphone|ipad|ipod|Macintosh/i.test(navigator.userAgent)) {
                window.store.register({
                    id: '358',
                    alias: '358',
                    type: window.store.CONSUMABLE
                });
                window.store.error(function (error) {
                    console.log('ERROR ' + error.code + ': ' + error.message);
                });
                window.store
                    .when('358')
                    .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 {
    loadSplash().then(res => {});
    window.$vm = app.mount('#app');
}
