import {
	req
} from '@/common/js/index.js';
import {
	loadValid as loadTraditionalTcmValid,
	save as saveTraditionalTcm,
	DEFAULT_TTL_MS,
} from '@/subPackages/sub_workbench/prescription_v2/utils/traditionalTcmLocalCache.js';

// 门店维度患者列表（全渠道挂号 + 当前门店），其它页面如需可继续调用
export function getPatientList(data) {
	return req.request({
		url: '/newApi/doctor-reception-wx/patient-list',
		method: 'GET',
		data
	})
}

/** 在线复诊患者列表（与 PC online-consultation/get-patient-list 一致；type: 1当前 2历史；可选 store_id） */
export function getOnlineConsultationPatientListApi(data) {
	return req.request({
		url: '/newApi/doctor-reception-wx/online-consultation-patient-list',
		method: 'GET',
		data
	})
}

// 获取正在接诊的患者列表
export function getAcceptingPatientList(data) {
	return req.request({
		url: '/newApi/doctor-reception-wx/accepting-patient-list',
		method: 'GET',
		data
	})
}

/** 工作台看板统计 */
export function getWorkbenchStats(data) {
	return req.request({
		url: '/newApi/doctor-reception-wx/workbench-stats',
		method: 'GET',
		data
	})
}

// 获取患者详情（挂号维度的就诊信息，不含处方列表）
export function getPatientItem(id) {
	return req.request({
		url: '/newApi/doctor-reception-wx/patient-item',
		method: 'GET',
		data: { id }
	})
}

/** 医生应用特色方到开方区 */
export function applySpecialPrescriptionApi(data) {
	return req.request({
		url: '/newApi/doctor-reception-wx/apply-special-prescription',
		method: 'POST',
		data
	})
}

/** 常用回复模板（与 PC online-consultation/get-quick-reply-list 同源） */
export function getQuickReplyListApi() {
	return req.request({
		url: '/newApi/doctor-reception-wx/get-quick-reply-list',
		method: 'GET'
	})
}

/** 本次挂号处方分页 */
export function getRegisterPrescriptionList(data) {
	return req.request({
		url: '/newApi/doctor-reception-wx/register-prescription-list',
		method: 'GET',
		data
	})
}

/** 患者历史处方分页（可排除某次挂号） */
export function getPatientPrescriptionHistory(data) {
	return req.request({
		url: '/newApi/doctor-reception-wx/patient-prescription-history',
		method: 'GET',
		data
	})
}

/** 撤回处方（待支付） */
export function withdrawPrescriptionWx(data) {
	return req.request({
		url: '/newApi/doctor-reception-wx/withdraw-prescription',
		method: 'POST',
		data
	})
}

/**
 * 根据患者ID获取患者信息
 * @param {number} patientId - 患者ID
 * @returns {Promise}
 */
export function getPatientInfoByPatientId(patientId) {
	return req.request({
		url: '/newApi/doctor-reception-wx/get-patient-info-by-patient-id',
		method: 'GET',
		data: { patient_id: patientId }
	})
}

// 接诊
export function receptionApi(id) {
	return req.request({
		url: '/newApi/doctor-reception-wx/reception',
		method: 'POST',
		data: { id }
	})
}

// 拒诊
export function refuseReceptionApi(data) {
	return req.request({
		url: '/newApi/doctor-reception-wx/refuse-reception',
		method: 'POST',
		data
	})
}

// 获取拒诊原因列表
export function refuseReceptionListApi() {
	return req.request({
		url: '/newApi/doctor-reception-wx/refuse-reception-list',
		method: 'GET'
	})
}

// 结束问诊
export function endOfDiagnosisApi(id) {
	return req.request({
		url: '/newApi/doctor-reception-wx/end-of-diagnosis',
		method: 'POST',
		data: { id }
	})
}

// 获取商品列表
export function getProductListDoctorReception(data) {
	return req.request({
		url: '/newApi/doctor-reception-wx/product-list',
		method: 'GET',
		data
	})
}

/** 中药全局快捷克数（与药品无关，每次打开中药抽屉拉取） */
export function getChineseMedicineQuickGramsApi() {
	return req.request({
		url: '/newApi/doctor-reception-wx/chinese-medicine-quick-grams',
		method: 'GET'
	})
}

// 获取药品使用方式列表
export function getDrugUseList() {
	return req.request({
		url: '/newApi/doctor-reception-wx/drug-use-list',
		method: 'GET'
	})
}

// 获取药品使用方式及默认用法用量
export function getDrugUseWithDefault(drugId) {
	return req.request({
		url: '/newApi/doctor-reception-wx/drug-use-with-default',
		method: 'GET',
		data: { drug_id: drugId }
	})
}

// 获取疾病列表
export function getDiseaseList(name, page = 1, pageSize = 20) {
	return req.request({
		url: '/newApi/doctor-reception-wx/disease-list',
		// url: '/doctor-reception-wx/disease-list',
		method: 'GET',
		data: { name, page, page_size: pageSize }
	})
}

// 获取医生的常用诊断列表
export function getMyDiseaseList() {
	return req.request({
		url: '/newApi/doctor-reception-wx/my-disease-list',
		method: 'GET'
	})
}

// 添加常用诊断
export function addMyDisease(diseaseId) {
	return req.request({
		url: '/newApi/doctor-reception-wx/add-my-disease',
		method: 'POST',
		data: { disease_id: diseaseId }
	})
}

// 删除常用诊断
export function deleteMyDisease(id) {
	return req.request({
		url: '/newApi/doctor-reception-wx/delete-my-disease',
		method: 'POST',
		data: { id }
	})
}

// 获取医嘱列表
export function getDoctorOrderList() {
	return req.request({
		url: '/newApi/doctor-reception-wx/doctor-order-list',
		// url: '/doctor-reception-wx/doctor-order-list',
		method: 'GET'
	})
}

// 创建医嘱
export function createDoctorOrder(content) {
	return req.request({
		url: '/newApi/doctor-reception-wx/create-doctor-order',
		method: 'POST',
		data: { content }
	})
}

// 删除医嘱
export function deleteDoctorOrder(id) {
	return req.request({
		url: '/newApi/doctor-reception-wx/delete-doctor-order',
		method: 'POST',
		data: { id }
	})
}

// 添加西药处方
export function addWestPrescription(data) {
	return req.request({
		url: '/newApi/doctor-reception-wx/add-west-prescription',
		method: 'POST',
		data
	})
}

/**
 * 按药品查可选配送仓（药店开方选仓）
 * 走 PC 同源 admin JWT 接口；医生小程序侧若无权限需后端另开 doctor 路由，此处与 delivery-warehouse-drug 对齐
 */
export function getDeliveryWarehouseOptionsByDrugs(data) {
	return req.request({
		url: '/newApi/doctor-reception-wx/delivery-warehouse-options-by-drugs',
		method: 'GET',
		data
	})
}

// 检查中药相冲
export function checkChineseMedicineConflictApi(data) {
	return req.request({
		url: '/newApi/doctor-reception-wx/check-chinese-medicine-conflict',
		method: 'POST',
		data
	})
}

function parseTraditionalTcmResponse(inner) {
	if (!inner || typeof inner !== 'object') return null;
	const { diseases, method, syndrome, expires_at, expires_at_ms, cache_ttl_seconds } = inner;
	if (!Array.isArray(diseases) || !Array.isArray(method) || !Array.isArray(syndrome)) {
		return null;
	}
	let expiresAtMs;
	if (typeof expires_at_ms === 'number' && expires_at_ms > Date.now()) {
		expiresAtMs = expires_at_ms;
	} else if (typeof expires_at === 'number' && expires_at > 0) {
		expiresAtMs = expires_at * 1000;
	} else {
		const ttlSec =
			typeof cache_ttl_seconds === 'number' && cache_ttl_seconds > 0
				? cache_ttl_seconds
				: DEFAULT_TTL_MS / 1000;
		expiresAtMs = Date.now() + ttlSec * 1000;
	}
	return {
		payload: { diseases, method, syndrome },
		expiresAtMs,
	};
}

/**
 * 中医证候/治法/疾病术语表：未过期读本地，否则 GET doctor-reception-wx（与 PC 同源数据 + 过期元数据）
 * @returns {Promise<{ diseases: array, method: array, syndrome: array }>}
 */
export function getTraditionalChineseMedicineJson() {
	const cached = loadTraditionalTcmValid();
	if (cached) {
		return Promise.resolve(cached);
	}
	return req
		.request({
			url: '/newApi/doctor-reception-wx/traditional-chinese-medicine-all',
			method: 'GET',
		})
		.then((res) => {
			if (res && res.wakaryReqToReject) {
				return Promise.reject(res);
			}
			const code = res && res.code;
			if (code != null && code !== 0 && code !== 200) {
				return Promise.reject(new Error((res && res.message) || 'traditional tcm api error'));
			}
			const inner = res && (res.result != null ? res.result : res.data);
			const parsed = parseTraditionalTcmResponse(inner);
			if (!parsed) {
				return Promise.reject(new Error('traditional tcm invalid'));
			}
			saveTraditionalTcm(parsed.payload, parsed.expiresAtMs);
			return parsed.payload;
		});
}

// 获取我的诊所列表
export function getMyStoreListApi() {
	return req.request({
		url: '/newApi/doctor-reception-wx/get-my-store-list',
		method: 'GET'
	})
}

// 获取当前诊所类型
export function getCurrentStoreTypeApi(data) {
	return req.request({
		url: '/newApi/doctor-reception-wx/get-current-store-type',
		method: 'GET',
		data
	})
}

// 订单百分比调价配置（开方前）
export function getPriceAdjustConfigApi(storeId) {
	return req.request({
		url: '/newApi/doctor-reception-wx/price-adjust-config',
		method: 'GET',
		data: storeId ? { store_id: storeId } : {}
	})
}

// 接诊页匹配推广员传方
export function getSalespersonTransferByRegisterApi(registerId) {
	return req.request({
		url: '/newApi/transfer-prescription/get-salesperson-by-register',
		method: 'GET',
		data: { register_id: registerId }
	})
}

// 切换诊所
export function switchStoreApi(data) {
	return req.request({
		url: '/newApi/doctor-reception-wx/switch-store',
		method: 'POST',
		data
	})
}

// 获取处方详情（医生小程序 doctor-reception-wx 路由，与接诊接口同鉴权）
export function getPrescriptionInfoApi(id) {
	return req.request({
		url: '/newApi/doctor-reception-wx/prescription-detail',
		method: 'GET',
		data: { id }
	})
}

// 获取加工规则列表
export function getProcessRuleList(data) {
	return req.request({
		url: '/newApi/doctor-reception-wx/process-rule-list',
		method: 'GET',
		data
	})
}

// 获取煎煮方式列表
export function getUseWayList() {
	return req.request({
		url: '/newApi/doctor-reception-wx/drug-use-way-list',
		method: 'GET'
	})
}

// 获取常用方列表
export function getCommonPrescriptionListApi(storeId) {
	return req.request({
		url: '/newApi/common-prescription/list',
		method: 'GET',
		data: { store_id: storeId }
	})
}

// 获取常用方详情
// 注意：prescription_v2 选用常用方已改走 list（与 PC 对齐，主表行 + 平行药品行一次返回），不再调用此接口
export function getCommonPrescriptionDetailApi(id, type) {
	return req.request({
		url: '/newApi/common-prescription/detail',
		method: 'GET',
		data: { id, type }
	})
}

// 保存西药常用方
export function saveWestCommonPrescriptionApi(data) {
	return req.request({
		url: '/newApi/common-prescription/save-west',
		method: 'POST',
		data
	})
}

// 保存中药常用方
export function saveChineseCommonPrescriptionApi(data) {
	return req.request({
		url: '/newApi/common-prescription/save-chinese',
		method: 'POST',
		data
	})
}

// 保存颗粒药/保健食品常用方
export function saveGranularCommonPrescriptionApi(data) {
	return req.request({
		url: '/newApi/common-prescription/save-granular',
		method: 'POST',
		data
	})
}

// 删除常用方
export function deleteCommonPrescriptionApi(data) {
	return req.request({
		url: '/newApi/common-prescription/delete',
		method: 'POST',
		data
	})
}

// 获取公共医嘱列表
export function getDoctorOrderCommonList(data) {
	return req.request({
		url: '/newApi/doctor-reception-wx/common-list',
		method: 'GET',
		data
	})
}

/** 根据挂号获取转诊处方信息（非转诊挂号时 result 为 null） */
export function getTransferPrescriptionByRegisterApi(register_id) {
	return req.request({
		url: '/newApi/doctor-reception-wx/transfer-prescription-by-register',
		method: 'GET',
		data: { register_id }
	})
}

/** 根据挂号与门店获取就诊经历药品列表（与 PC online-consultation/get-drugs-by-register-id 对齐） */
export function getDrugsByRegisterIdApi(data) {
	return req.request({
		url: '/newApi/doctor-reception-wx/get-drugs-by-register-id',
		method: 'GET',
		data: {
			register_id: data.register_id,
			store_id: data.store_id
		}
	})
}
