import dayjs from 'dayjs'
import { useRuntime } from '@/hooks/app/useRuntime'
import { Storage } from '@/utils/storage'

export interface Notice {
    /**
     * 通知 ID
     */
    id: number | string
    /**
     * 标题
     */
    title?: string
    /**
     * 内容
     */
    content: string
    /**
     * 按钮集合，confirm: 确认，exit: 退出
     */
    buttons?: string[]
    /**
     * 是否已确认
     */
    confirmed?: boolean
}

export interface NoticeMessage extends Notice {
    /**
     * 版本号（code）规则 JSON, 例如 { '>': '10000', '<': '20000' }
     */
    version?: Recordable

    /**
     * 平台，默认为 all，支持 'android' | 'ios' | 'harmonyos' | 'windows' | 'macos' | 'linux' | 'all'
     */
    os?: ['android' | 'ios' | 'harmonyos' | 'windows' | 'macos' | 'linux' | 'all']

    /**
     * 验证参数，用于校验当前用户是否需要弹出通知，例如：用户信息，租户信息等
     */
    verify: Recordable
}

/**
 * 检查是否有应用通知，如果有自动跳转到通知页面，没有则返回 false
 * @param verify 扩展校验参数，校验与通知中的 verify 字段一致
 * @returns Promise<boolean> 是否有应用通知
 */
export async function inspect(verify: Recordable = {}): Promise<boolean> {
    const { app } = useRuntime()
    const system = uni.getSystemInfoSync()
    const params = {
        datetime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        app: {
            id: system.appId,
            name: system.appName,
            version: system.appVersion,
            versionCode: system.appVersionCode,
            wgetVersion: app.value.version || system.appWgtVersion || system.appVersion,
            language: system.appLanguage,
        },
        os: {
            name: system.osName,
            version: system.osVersion,
        },
        net: {
            type: (await uni.getNetworkType()).networkType,
        },
        rom: {
            name: system.romName,
            version: system.romVersion,
        },
        device: {
            type: system.deviceType,
            brand: system.deviceBrand,
            model: system.deviceModel,
        },
        browser: {
            name: system.browserName,
            version: system.browserVersion,
            ua: system.ua,
        },
        runtime: {
            platform: system.platform,
            uniPlatform: system.uniPlatform,
            version: system.uniRuntimeVersion,
            compileVersion: system.uniCompileVersion,
            mode: import.meta.env.MODE,
            lastBuildTime: $app.lastBuildTime,
        },

        // 自定义校验参数（例如：用户信息/租户信息，可参与校验是否需要弹窗，实现精确到指定用户的提醒）
        verify,
    }

    try {
        // 调用云函数查询
        const result = await uniCloud.callFunction({
            name: 'app-notice-inspect',
            data: {
                params,
            },
        })
        const body = result.result as { id: number | string; params: typeof params; data: NoticeMessage }
        console.log('[Notice] Response', params, body)

        // 检查是否有通知
        const id = body.id
        if (!id) {
            return false
        }

        // 缓存通知数据
        const data: Notice = {
            id,
            confirmed: getConfirm(id),
            ...body.data,
        }
        getApp().globalData.notice = data

        if (!data.confirmed) {
            uni.navigateTo({ url: '/pages/common/notice/index' })
            return true
        }
    } catch (e) {
        console.warn(e)
    }

    return false
}

export function setConfirm(id: number | string) {
    if (getApp().globalData.notice) {
        Storage.set(`notice-${id}`, '1')
        getApp().globalData.notice.confirmed = true
    }
}

export function getConfirm(id: number | string) {
    return Storage.get(`notice-${id}`) === '1'
}
