/**
 * 解析转诊处方数据，输出与 PC TransferPrescriptionCard 一致的药品列表与诊断/医嘱。
 * @param {object|string} transferData 接口返回的 transfer 对象或 JSON 字符串
 * @returns {{ clinical_diagnose: string, doctor_order: string, drugList: array, prescription_type: number } | null}
 */
export function parseTransferPrescriptionContent(transferData) {
	let transferInfo = transferData;
	if (typeof transferInfo === 'string') {
		try {
			transferInfo = JSON.parse(transferInfo);
		} catch {
			return null;
		}
	}
	if (!transferInfo || typeof transferInfo !== 'object') return null;

	let prescriptionType = 1;
	if (transferInfo.prescription_type != null) {
		prescriptionType = Number(transferInfo.prescription_type) || 1;
	}

	if (transferInfo.prescription && transferInfo.prescription.content && Array.isArray(transferInfo.prescription.content)) {
		return {
			clinical_diagnose: transferInfo.prescription.clinical_diagnose || '',
			doctor_order: transferInfo.prescription.doctor_order || '',
			drugList: transferInfo.prescription.content,
			prescription_type: transferInfo.prescription.prescription_type != null ? Number(transferInfo.prescription.prescription_type) : prescriptionType
		};
	}

	const content = transferInfo.content;
	if (!content) return null;

	let drugList = [];
	if (typeof content === 'object' && !Array.isArray(content)) {
		if (content.repice && Array.isArray(content.repice)) {
			for (const recipe of content.repice) {
				if (recipe.content) {
					let recipeContent = recipe.content;
					if (typeof recipeContent === 'string') {
						try {
							recipeContent = JSON.parse(recipeContent);
						} catch {
							recipeContent = [];
						}
					}
					if (Array.isArray(recipeContent)) {
						drugList = drugList.concat(recipeContent);
					}
				}
			}
		}
		const orig = transferInfo.original_prescription || {};
		return {
			clinical_diagnose: content.clinical_diagnose || orig.clinical_diagnose || '',
			doctor_order: content.doctor_order || orig.doctor_order || '',
			drugList,
			prescription_type: prescriptionType
		};
	}
	if (Array.isArray(content)) {
		const orig = transferInfo.original_prescription || {};
		return {
			clinical_diagnose: orig.clinical_diagnose || '',
			doctor_order: orig.doctor_order || '',
			drugList: content,
			prescription_type: prescriptionType
		};
	}

	return null;
}

/**
 * 转诊处方接口 payload 归一化：空对象、无实质字段时视为无转诊卡，避免 v-if 误判为 true。
 * @param {object|null|undefined} data
 * @returns {object|null}
 */
export function normalizeTransferCardPayload(data) {
	if (data == null || typeof data !== 'object' || Array.isArray(data)) return null;
	const keys = Object.keys(data);
	if (keys.length === 0) return null;
	const has =
		(data.prescription_no != null && String(data.prescription_no).trim() !== '') ||
		(data.prescription && typeof data.prescription === 'object') ||
		(data.content != null && data.content !== '') ||
		(data.transfer_reason != null && String(data.transfer_reason).trim() !== '') ||
		(data.delegate_store && (data.delegate_store.name || data.delegate_store.id)) ||
		(data.transfer_store && (data.transfer_store.name || data.transfer_store.id)) ||
		(data.id != null &&
			data.id !== '' &&
			(data.status !== undefined && data.status !== null));
	if (!has) return null;
	return data;
}

/**
 * 转接方药品行 → 小程序中药处方行（对齐 PC convertDrugDataForImport + handleSelectSimpleProduct 最小字段）
 */
export function transferDrugToChineseRow(drug, prescriptionType) {
	const pt = prescriptionType != null ? Number(prescriptionType) : 1;
	const drugId = drug.drug_id || drug.id || 0;
	const name = drug.name || drug.drug_name || '';
	return {
		index_id: drug.id || drugId,
		id: drugId,
		drug_id: drugId,
		drug_name: name,
		number: drug.number != null ? Number(drug.number) : 1,
		price: drug.price != null ? parseFloat(drug.price) : 0,
		image: drug.image || '',
		instruction: drug.instruction || '',
		type: drug.type != null ? drug.type : pt,
		select_number: drug.select_number != null ? Number(drug.select_number) : drug.number != null ? Number(drug.number) : 1,
		specification: drug.specification || '',
		// 带上真实单位，避免导入后标签云仍显示默认 g
		unit_id: drug.unit_id || (drug.unit && drug.unit.id) || 0,
		unit: drug.unit || null,
		way_id: drug.way_id || 0,
	};
}

export function canImportTransferPrescription(transferCard) {
	const card = normalizeTransferCardPayload(transferCard);
	if (!card) return false;
	if (card.status === 3) return false;
	if (card.status === 2) return false;
	return true;
}
