import { req } from '@/common/js/index.js';
import { websocketConfig } from '@/config/websocket.js';

const PREFIX = '/newApi/doctor-chat-wx/';

/** 根据挂号解析/创建 IM 房间 */
export function getChatRoomByRegisterApi(register_id) {
	return req.request({
		url: `${PREFIX}chat-room-by-register`,
		method: 'GET',
		data: { register_id }
	});
}

/** 分页拉取房间历史消息（POST，与患者端一致） */
export function getMessagesByRoomIdApi(params) {
	return req.request({
		url: `${PREFIX}messages-by-room-id`,
		method: 'POST',
		data: params
	});
}

/** 挂号卡片信息（message_type=10 等） */
export function getChatRegisterInfoApi(params) {
	return req.request({
		url: `${PREFIX}chat-register-info`,
		method: 'GET',
		data: params
	});
}

/** 房间是否结束问诊等 */
export function getRoomStatusApi(params) {
	return req.request({
		url: `${PREFIX}get-room-status`,
		method: 'GET',
		data: params
	});
}

/** 聊天图片/语音上传 */
export function uploadChatFileApi(params) {
	return req.request({
		url: `${PREFIX}upload-chat-file`,
		type: 'upload',
		method: 'POST',
		filePath: params.filePath,
		name: params.name || 'file',
		formData: params.formData || {}
	});
}

function bearerAuthHeader() {
	let t = uni.getStorageSync('token') || '';
	if (!t) return {};
	t = String(t).replace(/^Bearer\s+/i, '').trim();
	if (!t) return {};
	return { Authorization: `Bearer ${t}` };
}

function unwrapLaravelInner(res) {
	if (res == null) return null;
	if (res.result !== undefined && res.result !== null) return res.result;
	if (res.data && res.data.result !== undefined) return res.data.result;
	return res.data != null ? res.data : res;
}

/** 判断 send-to-user 是否成功（兼容 Gin 与历史 Laravel jok） */
export function isSendToUserResponseOk(res) {
	if (res == null) return false;
	if (res.wakaryReqToReject) return false;
	if (res.status === 'success') return true;
	const c = Number(res.code);
	const ec = Number(res.errcode);
	if (!Number.isNaN(c) && c !== 0) return false;
	if (!Number.isNaN(ec) && ec !== 0) return false;
	const inner = unwrapLaravelInner(res);
	if (inner && typeof inner.status_code === 'number' && inner.status_code !== 200) return false;
	const body = inner && inner.body;
	if (body && body.error) return false;
	if (body && body.status === 'failure') return false;
	return true;
}

/** 发送失败提示文案 */
export function sendToUserFailMessage(res, err) {
	if (err && (err.msg || err.message)) return String(err.msg || err.message);
	if (res && res.msg) return String(res.msg);
	if (res && res.error) return String(res.error);
	const inner = unwrapLaravelInner(res);
	const body = inner && inner.body;
	if (body && body.error) return String(body.error);
	return '发送失败';
}

/** 从成功响应中取消息 id（Go 可能暂无，依赖 WS 合并） */
export function extractSendToUserMessageId(res) {
	if (!res || typeof res !== 'object') return null;
	if (res.id != null) return res.id;
	if (res.message_id != null) return res.message_id;
	const inner = unwrapLaravelInner(res);
	const body = inner && inner.body;
	const mid =
		body && (body.id != null ? body.id : body.message_id != null ? body.message_id : null);
	if (mid != null) return mid;
	if (inner && inner.id != null) return inner.id;
	if (res.data && (res.data.id != null || res.data.message_id != null)) {
		return res.data.id != null ? res.data.id : res.data.message_id;
	}
	return null;
}

/**
 * 直连 Go IM：POST /api/send-to-user（与 config/websocket.js 中 WS 同基址）
 * 不使用 PHP req 封装，避免加密与响应形态不一致。
 */
export function sendToUserHttpApi(params) {
	const url = websocketConfig.getSendToUserApiUrl();
	if (!url) {
		return Promise.reject({ msg: '未配置 IM 服务地址' });
	}
	const data = { ...params };
	if (data.platform == null && websocketConfig.user && websocketConfig.user.platform) {
		data.platform = websocketConfig.user.platform;
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url,
			method: 'POST',
			data,
			header: {
				'Content-Type': 'application/json',
				...bearerAuthHeader()
			},
			success: (r) => {
				const sc = Number(r.statusCode) || 0;
				const payload = r.data;
				const obj = payload && typeof payload === 'object' ? payload : null;
				if (sc < 200 || sc >= 300) {
					const msg =
						(obj && (obj.error || obj.message)) != null
							? String(obj.error || obj.message)
							: `HTTP ${sc}`;
					reject({ msg, data: payload, statusCode: sc });
					return;
				}
				if (obj && obj.error != null && obj.error !== '') {
					reject({ msg: String(obj.error), data: payload, statusCode: sc });
					return;
				}
				resolve(obj || {});
			},
			fail: (err) => {
				reject({ msg: (err && (err.errMsg || err.message)) || '网络错误', err });
			}
		});
	});
}
