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';

smoothscroll.polyfill();
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();
setTimeout(() => {
    onWindowResize();
}, 100);
Toast.setDefaultOptions('loading', { duration: 0 });
Dialog.setDefaultOptions({ theme: 'round-button' });
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('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 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 (location.pathname === '/hall') {
    if (query.id) {
        store.commit('setShowRoomId', query.id);
    }
}
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);
}
if (query.hopeMarket === 'true' || query.hopeMarket === true || sessionStorage.getItem('hopeMarket')) {
    store.commit('setHopeMarket', true);
    sessionStorage.setItem('hopeMarket', 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 (navigator.userAgent.includes('#cordova#')) {
    if (window.cordova && window.cordova.platformId) {
        store.commit('setPlatform', window.cordova.platformId);
    }
    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.styleLightContent();
            });
            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 {
    loadSplash().then(res => {
        window.$vm = app.mount('#app');
        calcSafeArea();
    });
    calcSafeArea();
}
