/** 解析扫码结果（与 xuexiaole-mobile-v useScanBind 一致） */
export const parseScanBindResult = (raw: string) => {
    if (!raw?.trim()) {
        throw new Error('无法识别扫描结果');
    }
    let json: Record<string, any>;
    try {
        json = JSON.parse(raw);
    } catch {
        throw new Error('无法识别扫描结果');
    }
    if (!json?.account || !json?.userId || !json?.simSerialNumber || !json?.model) {
        throw new Error('无法识别扫描结果');
    }
    return {
        account: String(json.account),
        childId: String(json.userId),
        simSerialNumber: String(json.simSerialNumber),
    };
};

/** 小程序扫码并跳转绑定确认页 */
export const scanAndGoBind = () => {
    uni.scanCode({
        onlyFromCamera: false,
        success: (res) => {
            try {
                const parsed = parseScanBindResult(res.result || '');
                const query = [
                    `childId=${encodeURIComponent(parsed.childId)}`,
                    `account=${encodeURIComponent(parsed.account)}`,
                    `simSerialNumber=${encodeURIComponent(parsed.simSerialNumber)}`,
                ].join('&');
                uni.navigateTo({ url: `/pages/parent/bind/index?${query}` });
            } catch (e: any) {
                uni.showToast({ title: e?.message || '无法识别扫描结果', icon: 'none' });
            }
        },
        fail: (err) => {
            const msg = err?.errMsg || '';
            if (msg.includes('cancel')) return;
            uni.showToast({ title: '扫码失败', icon: 'none' });
        },
    });
};
