/**
 * 直播间 WebSocket 协议（与 fs-live-ws WsSendMsgVo + R 包装一致）
 *
 * 下行格式：{ code: 200, msg: "...", data: { cmd, liveId, userId, data, status, on, ... } }
 * 上行格式：{ cmd, liveId, userId, userType, msg, nickName, avatar, data, status, duration }
 */

export const WS_CMD = {
	SEND_MSG: 'sendMsg',
	REPLY_USER: 'replyUser',
	HEARTBEAT: 'heartbeat',
	RED: 'red',
	GOODS: 'goods',
	COUPON: 'coupon',
	LIKE_DETAIL: 'likeDetail',
	LOTTERY: 'lottery',
	GLOBAL_VISIBLE: 'globalVisible',
	SINGLE_VISIBLE: 'singleVisible',
	SEND_POP_MSG: 'sendPopMsg',
	SEND_TOP_MSG: 'sendTopMsg',
	ENTRY: 'entry',
	OUT: 'out',
	LIVE_START: 'live_start',
	LIVE_END: 'live_end',
	INTEGRAL: 'Integral',
	USER_COUNT: 'userCount',
	DELETE_MSG: 'deleteMsg',
	LOTTERY_DETAIL: 'LotteryDetail',
	BLOCK_USER: 'blockUser',
	LIVE_QUIZ_START: 'liveQuizStart',
	LIVE_QUIZ_CLOSE: 'liveQuizClose',
	COMPLETION_POINTS: 'completionPoints',
	COMPLETION_POINTS_CONFIG: 'completionPointsConfig'
}

/** 解析 WebSocket 文本帧为统一 envelope */
export function parseWsEnvelope(raw) {
	if (raw == null || raw === '') {
		return null
	}
	let envelope
	try {
		envelope = typeof raw === 'string' ? JSON.parse(raw) : raw
	} catch (e) {
		return null
	}
	if (!envelope || typeof envelope !== 'object') {
		return null
	}
	const socketMessage = envelope.data
	if (!socketMessage || typeof socketMessage !== 'object') {
		return { envelope, socketMessage: null, code: envelope.code, msg: envelope.msg }
	}
	return {
		envelope,
		socketMessage,
		code: envelope.code,
		msg: envelope.msg
	}
}

/** 解析 data 字段中的 JSON 对象（已是对象则原样返回） */
export function parseJsonField(value, fallback = null) {
	if (value == null || value === '') {
		return fallback
	}
	if (typeof value === 'object') {
		return value
	}
	try {
		return JSON.parse(value)
	} catch (e) {
		return fallback
	}
}

/** 解析 data 字段中的数字（兼容 JSON 字符串化的数字） */
export function parseNumericField(value, fallback = 0) {
	if (value == null || value === '') {
		return fallback
	}
	if (typeof value === 'number' && !Number.isNaN(value)) {
		return value
	}
	const direct = Number(value)
	if (!Number.isNaN(direct)) {
		return direct
	}
	try {
		const parsed = JSON.parse(value)
		const num = Number(parsed)
		return Number.isNaN(num) ? fallback : num
	} catch (e) {
		return fallback
	}
}

export function isSuccessEnvelope(parsed) {
	return parsed && (parsed.code === 200 || parsed.code === '200')
}
