/**
 * 用户管理 / 就诊人档案 API（诊所管理员 / 平台超管）
 */
import { req } from '@/common/js/index.js';
import { unwrapClinicRes } from '@/api/clinicAdmin.js';

function getProfileContext() {
	const mode = uni.getStorageSync('loginMode');
	if (mode === 'clinic_admin') {
		return {
			prefix: '/newApi/clinic-admin-user-patient-profile',
			headerKey: '_clinicAdmin',
		};
	}
	return {
		prefix: '/newApi/platform-admin-user-patient-profile',
		headerKey: '_platformAdmin',
	};
}

function profileRequest(options) {
	const ctx = getProfileContext();
	return req.request({
		...options,
		header: {
			...(options.header || {}),
			[ctx.headerKey]: '1',
		},
	}).then((res) => {
		const data = unwrapClinicRes(res);
		// code 可能是数字 0 或字符串 "0"；勿用 === 导致 ok 为 false、列表被丢弃
		const ok = !!(res && (
			Number(res.code) === 0
			|| (res.errcode != null && Number(res.errcode) !== -1)
		));
		return { res, data, ok };
	});
}

/**
 * 从 profile 接口包装中取出列表 items（兼容 result/data/items 多层）
 */
export function pickProfileItems(wrap) {
	const raw = (wrap && wrap.data) || null;
	const body = wrap && wrap.res;
	const fromBody = body && (body.result || body.data);
	let payload = raw;
	// unwrap 后若仍带着 code/result，再剥一层
	if (payload && payload.items == null && payload.result != null) {
		payload = payload.result;
	}
	if (payload == null && fromBody) {
		payload = fromBody;
	}
	if (Array.isArray(payload)) {
		return payload;
	}
	if (payload && Array.isArray(payload.items)) {
		return payload.items;
	}
	if (payload && Array.isArray(payload.list)) {
		return payload.list;
	}
	return [];
}

export function getUserPatientList(params) {
	const { prefix } = getProfileContext();
	return profileRequest({ url: `${prefix}/list`, method: 'GET', data: params });
}

/** 会员管理：微信用户分页列表 */
export function getWxUserList(params) {
	const { prefix } = getProfileContext();
	return profileRequest({ url: `${prefix}/user-list`, method: 'GET', data: params });
}

/** 某微信用户下的就诊人列表 */
export function getPatientListByUser(userId) {
	const { prefix } = getProfileContext();
	return profileRequest({
		url: `${prefix}/patient-list-by-user`,
		method: 'GET',
		data: { user_id: userId },
	});
}

export function getUserPatientDetail(upId) {
	const { prefix } = getProfileContext();
	return profileRequest({
		url: `${prefix}/detail`,
		method: 'GET',
		data: { up_id: upId },
	});
}

export function getUserPatientRegisterList(upId, params) {
	const { prefix } = getProfileContext();
	return profileRequest({
		url: `${prefix}/register-list`,
		method: 'GET',
		data: { up_id: upId, ...params },
	});
}

/** 就诊人单次挂号详情（基本信息 + 选药 + 回答记录） */
export function getUserPatientRegisterDetail(registerId) {
	const { prefix } = getProfileContext();
	return profileRequest({
		url: `${prefix}/register-detail`,
		method: 'GET',
		data: { register_id: registerId },
	});
}

export function getUserPatientPrescriptionList(upId, params) {
	const { prefix } = getProfileContext();
	return profileRequest({
		url: `${prefix}/prescription-list`,
		method: 'GET',
		data: { up_id: upId, ...params },
	});
}

export function getUserPatientOrderList(upId, params) {
	const { prefix } = getProfileContext();
	return profileRequest({
		url: `${prefix}/order-list`,
		method: 'GET',
		data: { up_id: upId, ...params },
	});
}

/**
 * 就诊人回访记录列表
 * @param {number|string} upId 就诊人ID
 * @param {object} params { pageSize }
 */
export function getPatientCallLogList(upId, params) {
	const { prefix } = getProfileContext();
	return profileRequest({
		url: `${prefix}/call-log-list`,
		method: 'GET',
		data: { up_id: upId, ...(params || {}) },
	});
}

/**
 * 创建就诊人回访记录
 * @param {number|string} upId 就诊人ID
 * @param {object} payload { phone, call_at, result, tags, conclusion, remark, next_at }
 */
export function createPatientCallLog(upId, payload) {
	const { prefix } = getProfileContext();
	return profileRequest({
		url: `${prefix}/call-log-create`,
		method: 'POST',
		data: { up_id: upId, ...(payload || {}) },
	});
}

/**
 * 小程序回访字典（启用中的结果/标签 + 颜色）
 * 返回结构：{ results: [{value,name,color}], tags: [...] }
 */
export function getPatientCallLogDict() {
	const { prefix } = getProfileContext();
	return profileRequest({
		url: `${prefix}/call-log-dict`,
		method: 'GET',
	});
}
