import { reactive, toRefs, readonly } from 'vue'

export default new (class {
    private _state = reactive({
        layout: 'default', // 页面布局
        clientWidth: 0, // 客户端宽度
        isMobile: false, // 是否移动设备
    })

    /** 只读状态 */
    state = readonly(this._state);

    /**
     * 适配客户端屏幕
     * @param pxtorem rem 布局
     */
    screenAdapter(pxtorem: boolean) {
        const { clientWidth, isMobile } = toRefs(this._state);
        const { isPc } = this.getClientAgent();
        const el = document.documentElement;
        const body = document.body;
        let screenWidth = el.clientWidth;

        if (pxtorem) {
            const designSize = 750;
            isMobile.value = true;

            if (isPc) {
                screenWidth = designSize / 1.8;
                body.style.setProperty('width', '540px');
            } else {
                body.style.removeProperty('width')
            }

            if (screenWidth > 0) {
                const fontSize = (screenWidth / designSize) * 100 + 'px';
                el.style.setProperty('font-size', fontSize);
            }
        } else {
            if (screenWidth > 768) {
                isMobile.value = false;
            } else {
                isMobile.value = true;
            }

            el.setAttribute('screen', isMobile.value ? 'small' : 'normal');
        }

        clientWidth.value = body.clientWidth;
    }

    /**
     * 获取客户端平台
     * @returns 
     */
    getClientAgent() {
        const ua = navigator.userAgent,
            isWindowsPhone = /(?:Windows Phone)/.test(ua),
            isSymbian = /(?:SymbianOS)/.test(ua) || isWindowsPhone,
            isAndroid = /(?:Android)/.test(ua),
            isFireFox = /(?:Firefox)/.test(ua),
            isChrome = /(?:Chrome|CriOS)/.test(ua),
            isTablet = /(?:iPad|PlayBook)/.test(ua) || (isAndroid && !/(?:Mobile)/.test(ua)) || (isFireFox && /(?:Tablet)/.test(ua)),
            isiPhone = /(?:iPhone)/.test(ua) && !isTablet,
            isPc = !isiPhone && !isAndroid && !isSymbian;

        return {
            isTablet,
            isiPhone,
            isAndroid,
            isChrome,
            isPc,
        }
    }
})