'use strict'
exports.main = async (event, context) => {
    // eslint-disable-next-line no-undef
    const db = uniCloud.database()
    const dbCmd = db.command
    const { total } = await db.collection('opendb-app-list').where({ appid: context.appId }).count()
    if (total < 1) {
        return { errCode: 1, errMsg: '应用信息不存在' }
    }

    // 查询优先级最高且在生效中的 APP 通知
    const { params } = event
    const { data: notices } = await db
        .collection('app-notice')
        .where({
            appid: context.appId,
            enabled: true,
            expired: dbCmd.gt(Date.now()),
        })
        .orderBy('priority', 'asc')
        .limit(1)
        .get()
    if (notices.length < 1) {
        return { errCode: 1, errMsg: '暂无生效中的通知' }
    }

    // 获取通知信息
    const notice = notices[0]
    console.log('notice', notice)

    // 检查运行环境
    if (notice.mode !== params.runtime.mode) {
        return { errCode: 1, errMsg: '运行环境不匹配', message: `${params.runtime.mode} -> ${notice.mode}` }
    }

    // 检查平台
    if (notice.os && notice.os.length > 0 && !notice.os.includes('all') && !notice.os.includes(params.os.name)) {
        return { errCode: 1, errMsg: '平台不匹配', message: `${params.os.name} -> ${JSON.stringify(notice.os)}` }
    }

    // 检查版本号
    if (notice.version) {
        const keys = Object.keys(notice.version)
        const code = Number(
            context.appWgtVersion
                .split('.')
                .map((v) => String(v).padStart(2, '0'))
                .join(''),
        )
        const mismatching = keys
            .map((v) => {
                switch (v) {
                    case '>':
                        if (code <= notice.version[v]) {
                            return false
                        }
                        break
                    case '<':
                        if (code >= notice.version[v]) {
                            return false
                        }
                        break
                    case '=':
                        if (code !== notice.version[v]) {
                            return false
                        }
                        break
                    case '>=':
                        if (code < notice.version[v]) {
                            return false
                        }
                        break
                    case '<=':
                        if (code > notice.version[v]) {
                            return false
                        }
                        break
                    default:
                        return false
                }

                return true
            })
            .some((v) => !v)
        if (mismatching) {
            return {
                errCode: 1,
                errMsg: '版本号不匹配',
                message: `${context.appWgtVersion} -> ${code} -> ${JSON.stringify(notice.version)}`,
            }
        }
    }

    // 检查自定义参数
    const verifyKeys = Object.keys(params.verify)
    if (
        verifyKeys.length < Object.keys(notice.verify).length ||
        verifyKeys.some((v) => notice.verify[v] !== params.verify[v])
    ) {
        return {
            errCode: 1,
            errMsg: '校验参数不匹配',
            message: `${JSON.stringify(params.verify)} -> ${JSON.stringify(notice.verify)}`,
        }
    }

    // 返回数据给客户端
    return {
        id: notice._id,
        params: {
            app: params.app,
            verify: params.verify,
        },
        data: {
            ...notice,
        },
    }
}
