/**
 * 设备信息采集 + 持久化 device_id
 */
import { registerDevice, type DeviceRegisterPayload } from '@/api/device'

const DEVICE_ID_KEY = 'app_device_id'

/** 生成或读取持久化的 device_id（UUID v4 简化版） */
export function getOrCreateDeviceId(): string {
    try {
        const cached = uni.getStorageSync(DEVICE_ID_KEY)
        if (cached) return cached
    } catch (e) {
        /* ignore */
    }

    const id = generateUUID()
    try {
        uni.setStorageSync(DEVICE_ID_KEY, id)
    } catch (e) {
        /* ignore */
    }
    return id
}

function generateUUID(): string {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
        const r = (Math.random() * 16) | 0
        const v = c === 'x' ? r : (r & 0x3) | 0x8
        return v.toString(16)
    })
}

/** 当前平台标识 */
export function getPlatform(): string {
    // #ifdef H5
    return 'h5'
    // #endif
    // #ifdef MP-WEIXIN
    return 'mp_weixin'
    // #endif
    // #ifdef APP-PLUS
    try {
        const sys = uni.getSystemInfoSync()
        const p = (sys.platform || '').toLowerCase()
        if (p === 'ios') return 'ios'
        if (p === 'android') return 'android'
        if (p === 'windows') return 'windows'
        if (p === 'mac') return 'mac'
        return p || 'app'
    } catch (e) {
        return 'app'
    }
    // #endif
    return 'unknown'
}

/** 收集设备信息 */
export function collectDeviceInfo(): DeviceRegisterPayload {
    const deviceId = getOrCreateDeviceId()
    const platform = getPlatform()

    let sys: any = {}
    try {
        sys = uni.getSystemInfoSync()
    } catch (e) {
        /* ignore */
    }

    let networkType = ''
    try {
        // 同步获取（部分平台不支持）
        // @ts-ignore
        const net = (uni as any).getNetworkType?.sync?.()
        if (net && net.networkType) networkType = net.networkType
    } catch (e) {
        /* ignore */
    }

    return {
        device_id: deviceId,
        platform,
        system: [sys.osName, sys.osVersion || sys.system].filter(Boolean).join(' '),
        model: sys.model || sys.deviceModel || '',
        brand: sys.brand || sys.deviceBrand || '',
        app_version: sys.appVersion || '',
        app_version_code: Number(sys.appWgtVersion || sys.appVersionCode || 0) || 0,
        screen_width: sys.screenWidth || sys.windowWidth || 0,
        screen_height: sys.screenHeight || sys.windowHeight || 0,
        network_type: networkType,
        language: sys.language || sys.osLanguage || '',
        timezone: (typeof Intl !== 'undefined' ? Intl.DateTimeFormat().resolvedOptions().timeZone : '') || '',
    }
}

/** 上报设备信息（失败不影响主流程） */
export async function reportDevice(): Promise<void> {
    try {
        const payload = collectDeviceInfo()

        // 异步获取网络类型并补上
        try {
            await new Promise<void>((resolve) => {
                uni.getNetworkType({
                    success: (res) => {
                        payload.network_type = res.networkType || ''
                        resolve()
                    },
                    fail: () => resolve(),
                })
            })
        } catch (e) {
            /* ignore */
        }

        await registerDevice(payload)
    } catch (e) {
        console.warn('[device] 设备信息上报失败:', e)
    }
}
