<template>	<full-page mainStyle="background:#f0f0f0" @reachBottom="loadMore" :class="{ 'elder-mode': elderMode }">
		<template v-if="logined">
			<template v-if="list.length">
				<view class="history-order-title">历史诊疗记录</view>
				<view v-for="item in list" class="card" :class="{ 'card--elder': elderMode }">
					<view class="card_head info-row" :class="{ 'card_head--elder': elderMode }">
						<view class="doctor-info" :class="{ 'doctor-info--elder': elderMode }">
							<text>{{ item.doctorName }}</text>
							<text class="dept" :class="{ 'dept--elder': elderMode }">{{ item.deptName }}</text>
						</view>
						<view v-if="item.statusTxt" class="status" :class="{ 'status-text--elder': elderMode }" :style="{ color: item.statusColor }">
							{{ item.statusTxt }}
						</view>
					</view>
					<view class="card_body" :class="{ 'card_body--elder': elderMode }">
						<view>
							<text class="label" :class="{ 'label--elder': elderMode }">线下确诊疾病：</text>
							<text :class="{ 'body-text--elder': elderMode }">{{ item.diseases.join('、') }}</text>
						</view>
						<view class="desc" :class="{ 'desc--elder': elderMode }">
							<text class="label" :class="{ 'label--elder': elderMode }">病情描述：</text>
							<text :class="{ 'body-text--elder': elderMode }">{{ item.description }}</text>
						</view>
						<view class="info-row" :class="{ 'info-row--elder': elderMode }">
							<view>
								<text class="label" :class="{ 'label--elder': elderMode }">问诊人：</text>
								<text :class="{ 'body-text--elder': elderMode }">{{ item.name }} {{ item.sex }} {{ item.age ? item.age + '岁' : '' }}</text>
							</view>
							<view :class="{ 'body-text--elder': elderMode }">
								{{ item.createTime ? dayjs(item.createTime).format('YYYY-MM-DD HH:mm') : '' }}
							</view>
						</view>
					</view>
					<view class="card_footer info-row-end" :class="{ 'card_footer--elder': elderMode }">
						<view :class="{ 'footer-type--elder': elderMode }">
							{{ item.preOrderId ? '在线续方' : '在线复诊' }}
						</view>
						<view class="import-btn" :class="{ 'import-btn--elder': elderMode }" @click="useRecord(item)">导入</view>
					</view>
				</view>
			</template>
			<empty-data v-else text="无历史诊疗记录">
				<div class="empty-container" @click="consult()">
					<text>请点击</text>
					<view class="consult-button">在线复诊</view>
					<text>发起问诊申请</text>
				</div>
			</empty-data>

		</template>
		<re-login v-else height="80vh" />
	</full-page>
</template>
<script setup>
	import {
		onLoad
	} from "@dcloudio/uni-app";
	import {
		ref,
		watch,
		onMounted,
		onUnmounted
	} from 'vue';
	import dayjs from 'dayjs';
	import useUser from '@/hooks/useUser';
	import orderStore from '@/store/order';
	import {
		getOrderStatus
	} from '@/utils'
	import {
		getConsultOrder
	} from '@/utils/api.js';
	import {
		bindHisPatient
	} from "@/utils/api";
	import { toast } from "@/utils/widget";
	
	import fullPage from '@/components/full-page.vue';
	import reLogin from '@/components/re-login.vue';
	import emptyData from "@/components/empty.vue";
	import ybPlugin from "@/utils/insurance-plugin";
	const {
		userInfo,
		logined,
		cards,
		card,
		getAuthCode,
		idCardInfo
	} = useUser();
	const {
		reuse
	} = orderStore();
	const page = ref(1);
	const list = ref([])
	const more = ref(false);
	const loading = ref(false);


	onLoad(() => {
		ybPlugin.init({
			tokenCallback: () => {
			  uni.redirectTo({
			    url: "/pages/consult/select-history-order",
			  });
			}
		});
	});

	function loadMore() {
		if (more.value && !loading.value) {
			page.value++;
			getList();
		}
	}
	async function getList() {
		if (loading.value) return;
		loading.value = true;
		const {
			data,
			pages
		} = await getConsultOrder({
			page: page.value,
			pageSize: 20,
			patientId: card.value.patientId,
			idCard: userInfo.value.certNo,
			showPassdiagnostic: true,
			hasPassDiagnostic: true
		});
		const listData = Array.isArray(data) ? data.map(i => {
			const {
				text: statusTxt,
				color: statusColor
			} = getOrderStatus(i);
			return {
				...i,
				statusTxt,
				statusColor
			}
		}) : [];
		list.value = page.value === 1 ? listData : [...list.value, ...listData];
		more.value = pages > page.value;
		loading.value = false;
	}

	async function useRecord(item) {
		const authCode = await getAuthCode("nhsamp");
		const psnToken = await ybPlugin.getArchiveToken(authCode);
		if (psnToken) {
			await bindInsurance(psnToken);
		}
		if (typeof card.value.address !== 'string' || card.value.address.trim() === '') {
			await confirm('请完善地址信息', {
				showCancel: false
			});
			uni.navigateTo({
				url: '/pages/member/detail'
			})
			return
		}
		
		reuse(item);
		uni.navigateTo({
			url: `/pages/consult/confirm?doctorNo=${item.doctorCode || ''}&unitCode=${item.unitCode || ''}&preOrderId=${item.orderId}`
		})
		// if (typeof card.value.address !== 'string' || card.value.address.trim() === '') {
		// 	await confirm('请完善地址信息', {
		// 		showCancel: false
		// 	});
		// 	const authCode = await getAuthCode("nhsamp");
		// 	const psnToken = await ybPlugin.getArchiveToken(authCode);
		// 	try {
		// 		await bindInsurance(psnToken);
		// 		reuse(item);
		// 		uni.navigateTo({
		// 			url: `/pages/consult/confirm?doctorNo=${item.doctorCode || ''}&unitCode=${item.unitCode || ''}&preOrderId=${item.orderId}`
		// 		})
		// 	} catch (e) {
		// 		toast(e);
		// 	}
		// 	uni.navigateTo({
		// 		url: '/pages/member/detail'
		// 	})
		// 	return
		// }


	}

	async function bindInsurance(psnToken) {
		const {
			success,
			list,
			message
		} = await bindHisPatient({
			idCard: userInfo.value.certNo,
			name: userInfo.value.userName,
			mobile: userInfo.value.mobile,
			psnToken,
		});
		if (success) {
			cards.value = Array.isArray(list) ? list : [];
		} else {
			toast(message)
			return Promise.reject(message);
		}
	}

	function consult() {
		uni.redirectTo({
			url: '/pages/consult/index'
		})
	}

	watch(logined, n => {
		if (n) {
			page.value = 1;
			getList()
		}
	}, {
		immediate: true
	})

	// 长辈模式状态
const elderMode = ref(false);
function handleElderModeChange(isElder) {
	elderMode.value = isElder;
}

onMounted(() => {
	const savedElderMode = uni.getStorageSync('elderMode');
	if (savedElderMode !== null && savedElderMode !== undefined) {
		elderMode.value = savedElderMode;
	}
	const app = getApp();
	if (app && app.globalData && typeof app.globalData.elderMode === 'boolean') {
		elderMode.value = app.globalData.elderMode;
	}
	uni.$on('elderModeChanged', handleElderModeChange);
});
onUnmounted(() => {
	uni.$off('elderModeChanged', handleElderModeChange);
});
</script>
<style lang="scss" scoped>
	.history-order-title {
		padding: 24rpx 30rpx;
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}
	/* 长辈模式特定样式 */
	.card {
		background: white;

		@at-root &+& {
			margin-top: 20rpx;
		}

		// 适老化模式：卡片整体变大
		@at-root &--elder {
			margin: 30rpx 20rpx;
			border-radius: 16rpx;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
		}

		.info-row {
			display: flex;
			align-items: center;
			justify-content: space-between;

			// 适老化模式：元素各占一行
			@at-root &--elder {
				flex-direction: column;
				align-items: flex-start;
				gap: 16rpx;
			}
		}

		.info-row-end {
			display: flex;
			align-items: center;
			justify-content: space-between;

			// 适老化模式：元素各占一行
			@at-root &--elder {
				flex-direction: column;
				align-items: flex-start;
				gap: 20rpx;
			}
		}

		&_head {
			padding: 24rpx 30rpx;
			font-size: 28rpx;
			color: #333;
			border-bottom: 1px solid #e5e5e5;

			// 适老化模式：头部内边距增加，字体放大
			@at-root &--elder {
				padding: 36rpx 40rpx;
				font-size: 39rpx; // 28 * 1.4
				font-weight: bold;
			}
		}

		&_footer {
			padding: 24rpx 30rpx;
			font-size: 28rpx;
			color: $theme-brown-primary;
			border-top: 1px solid #e5e5e5;

			// 适老化模式：底部内边距增加，字体放大
			@at-root &--elder {
				padding: 36rpx 40rpx;
				font-size: 39rpx; // 28 * 1.4
				font-weight: bold;
			}

			.import-btn {
				padding: 6rpx 30rpx;
				border: 1px solid;
				border-radius: 30rpx;

				// 适老化模式：按钮变大
				@at-root &--elder {
					padding: 12rpx 40rpx;
					font-size: 35rpx; // 25 * 1.4 (按钮字体稍小)
					border-radius: 40rpx;
					margin-right: 20rpx !important;
					font-weight: bold;
					margin-bottom: 12rpx; // 按钮间垂直间距
				}
			}
		}

		.doctor-info {
			font-weight: bold;
			max-width: 400rpx;
			white-space: nowrap;
			text-overflow: ellipsis;
			overflow: hidden;
			line-height: 48rpx;
			font-size: 30rpx;

			// 适老化模式：医生信息字体放大
			@at-root &--elder {
				max-width: 100%;
				white-space: normal; // 允许换行
				text-overflow: unset;
				overflow: visible;
				line-height: 60rpx;
				font-size: 42rpx; // 30 * 1.4
				font-weight: bold;
			}
		}

		.dept {
			margin-left: 10rpx;
			color: #666;
			font-weight: normal;
			font-size: 28rpx;

			// 适老化模式：科室字体放大
			@at-root &--elder {
				margin-left: 20rpx; // 科室左边距
				font-size: 39rpx; // 28 * 1.4
				font-weight: 500;
				margin-top: 8rpx;
			}
		}

		.status {
			color: red;
		}

		&_body {
			padding: 24rpx 30rpx;
			font-size: 28rpx;
			line-height: 48rpx;
			color: #333;

			// 适老化模式：内容区域内边距增加，字体和行高放大
			@at-root &--elder {
				padding: 36rpx 40rpx;
				font-size: 39rpx; // 28 * 1.4
				line-height: 67rpx; // 48 * 1.4
				font-weight: 500;
			}

			.label {
				color: #666;

				// 适老化模式：标签字体放大
				@at-root &--elder {
					font-size: 39rpx; // 28 * 1.4
				}
			}

			.desc {
				display: -webkit-box;
				-webkit-box-orient: vertical;
				-webkit-line-clamp: 2;
				line-clamp: 2;
				overflow: hidden;

				// 适老化模式：描述区域行数增加，便于阅读
				@at-root &--elder {
					-webkit-line-clamp: 4;
					line-clamp: 4;
				}
			}

			// 适老化模式：每个信息块单独占一行
			@at-root &--elder > view {
				margin-bottom: 16rpx;
			}
		}
	}

	.empty-container {
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 28rpx;
		color: #333;
		padding-top: 40rpx;

		.consult-button {
			padding: 6rpx 20rpx 10rpx;
			border-radius: 8rpx;
			color: white;
			margin: 0 10rpx;
			background: $theme-brown-primary;
		}
	}

	// 适老化模式额外样式类
	.status-text--elder {
		font-size: 39rpx !important; // 28 * 1.4
		font-weight: bold;
	}

	.body-text--elder {
		font-size: 39rpx !important; // 28 * 1.4
		font-weight: 500;
	}

	.footer-type--elder {
		font-size: 39rpx !important; // 28 * 1.4
		font-weight: bold;
	}
</style>