import { createApp } from 'vue';
import App from './App.vue';
import './registerServiceWorker';
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';
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('https://nft.9space.vip//redirect?redirectUrl=' + location.href);
    // }
}
if (query.invitor) {
    store.commit('setInvitor', query.invitor);
}
if (query.inviteCode) {
    store.commit('setInviteCode', query.inviteCode);
}
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)');
if (navigator.userAgent.includes('#cordova#')) {
    document.addEventListener(
        'deviceready',
        function () {
            new Promise((resolve, reject) => {
                if (navigator.appInfo) {
                    http.http.get(`/appVersion/checkIosReview?version=${navigator.appInfo.version}`).then(res => {
                        store.commit('setReview', res.review);
                        if (res.review) {
                            if (location.host !== 'test.raex.vip') {
                                location.href = 'https://test.raex.vip';
                                return;
                            }
                        }
                        resolve();
                    });
                } else {
                    resolve();
                }
            }).then(() => {
                window.$vm = app.mount('#app');
                StatusBar.overlaysWebView(false);
                StatusBar.hide();
                setTimeout(() => {
                    navigator.splashscreen.hide();
                    StatusBar.show();
                    StatusBar.backgroundColorByHexString('#F5F7FA');
                    StatusBar.styleDefault();
                }, 2000);

                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 (
                    !(
                        location.host === 'www.raex.vip' ||
                        location.host === 'test.raex.vip' ||
                        /^http:\/\/192\.168\.\d{1,3}\.\d{1,3}((:\d+)?)$/.test(location.host)
                    )
                ) {
                    if (!/iphone|ipad|ipod/i.test(navigator.userAgent)) {
                        window.$vm.$dialog.alert({
                            message: '检测到新版本，请下载更新',
                            confirmButtonText: '下载更新',
                            beforeClose(action, done) {
                                console.log(action);
                                if (/iphone|ipad|ipod/.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/i.test(navigator.userAgent)) {
                    window.store.register({
                        id: '358',
                        alias: 'my_consumable1',
                        type: window.store.CONSUMABLE
                    });

                    window.store.error(function (error) {
                        console.log('ERROR ' + error.code + ': ' + error.message);
                    });
                    window.store
                        .when('358')
                        .updated(product => {
                            console.log(product, 'updated');
                            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 => {
                            emitter.emit('iapEvent', { event: 'approved', product });
                            window.store.get('358').finish();
                        })
                        .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');
}
