import { APP_UUID_KEY } from '/@/enums/cacheEnum'
import { nanoid } from 'nanoid'
import md5 from 'crypto-js/md5'
import { Storage } from '@/utils/storage'
import { tryOnMounted } from '@vueuse/core'

interface DeviceInfo {
    uuid: string
    vendor: string
    model: string
}

export interface Runtime {
    app: Ref<PlusRuntimeWidgetInfo>
    getDeviceInfo: () => Promise<DeviceInfo>
}

export function useRuntime(): Runtime {
    const app = ref<PlusRuntimeWidgetInfo>({})

    tryOnMounted(() => {
        // 获取应用信息
        // #ifdef APP-PLUS
        plus.runtime.getProperty(plus.runtime.appid, (info) => {
            app.value = info
        })
        // #endif
    })

    /**
     * 获取设备信息
     * 注意: 需要在页面的 onReady 后使用
     * @returns 设备信息
     */
    function getDeviceInfo(): Promise<DeviceInfo> {
        return new Promise((resolve, reject) => {
            // #ifdef APP-PLUS
            plus.device.getInfo({
                success: resolve,
                fail: reject,
            })
            // #endif

            // #ifndef APP-PLUS
            let uuid = uni.getStorageSync(APP_UUID_KEY)
            if (!uuid) {
                uuid = md5(nanoid()).toString()
                Storage.set(APP_UUID_KEY, uuid)
            }
            const result = { uuid, vendor: 'unknown', model: 'unknown' }
            const userAgent = navigator.userAgent
            const deviceInfo = userAgent.match(/\((.*?)\)/)
            if (deviceInfo && deviceInfo.length > 1) {
                const info = deviceInfo[1].split(';')
                if (/android/i.test(userAgent)) {
                    if (info.length >= 3) {
                        result.vendor = info[1].trim()
                        result.model = info[2].trim()
                    }
                } else {
                    result.vendor = info[0].trim()
                    result.model = info[1].trim()
                }
            }
            resolve(result)
            // #endif
        })
    }

    return {
        app,
        getDeviceInfo,
    }
}
