<template>
<view class="container">
	<!-- 就诊人信息弹窗 -->
	<view v-if="showPatientModal" class="modal-overlay" @click.self="() => {}">
		<view class="patient-modal">
			<view class="modal-title">就诊人信息</view>
			<view class="patient-info-box">
				<view class="info-row">{{ formData.patient_name || '-' }}  {{ formData.gender === 1 ? '男' : '女' }}  {{ formData.age || '-' }}岁</view>
				<view class="info-row">体重：{{ formData.weight ? formData.weight + ' KG' : '-' }}</view>
				<view class="info-row">身高：{{ formData.height ? formData.height + ' CM' : '-' }}</view>
				<view class="info-row">血压：{{ (formData.systolic_pressure && formData.diastolic_pressure) ? (formData.systolic_pressure + '/' + formData.diastolic_pressure + ' mmHg') : '' }} mmHg</view>
				<view class="info-row">空腹血糖：{{ formData.fasting_blood_sugar ? formData.fasting_blood_sugar + ' mmol/L' : '-' }}</view>
				<view class="info-row">发现糖尿病患病史：{{ formatDiabetesDiscovery(formData.diabetes_discovery_year) }}</view>
				<view class="info-row">当地医院诊断：{{ getLocalDiagnosisText() }}</view>
				<view class="info-row">当地就诊医院名称：{{ formData.local_hospital_name || '-' }}</view>
				<view class="info-row">当地医院就诊时间：{{ formData.diagnosis_date || formData.local_hospital_visit_time || '-' }}</view>
			</view>
			<view class="agreement-row">
				<text>我已阅读并同意</text>
				<text class="agreement-link" @click="openConsentForm">《互联网诊疗知情同意书》</text>
			</view>
			<button class="modal-confirm-btn" :disabled="confirmBtnLoading" :loading="confirmBtnLoading" @click="closePatientModal">点击确认并开始视频问诊</button>
		</view>
	</view>
	
	<view v-if="false">
		<!-- 确认成功页面 -->
		<view v-if="showSuccessPage" class="success-page">
			<view class="success-icon">✓</view>
			<view class="success-title">确认成功</view>
			<view class="success-desc">诊单已确认，感谢您的配合</view>
			<button class="back-btn" @click="goBack">返回</button>
		</view>
		
		<!-- 诊单详情表单 -->
		<view v-else class="form-wrapper">
			<!-- 基本信息 -->
			<view class="section">
				<view class="section-title">基本信息</view>
				
				<view class="info-item">
					<text class="label">患者姓名</text>
					<text class="value">{{ formData.patient_name || '-' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">身份证号</text>
					<text class="value">{{ formData.id_card || '-' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">手机号</text>
					<text class="value">{{ formData.phone || '-' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">性别</text>
					<text class="value">{{ formData.gender === 1 ? '男' : '女' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">年龄</text>
					<text class="value">{{ formData.age || '-' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">诊断日期</text>
					<text class="value">{{ formData.diagnosis_date || '-' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">诊断类型</text>
					<text class="value">{{ getDiagnosisTypeName() || '-' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">证型</text>
					<text class="value">{{ getSyndromeTypeName() || '-' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">糖尿病期数</text>
					<text class="value">{{ getDiabetesTypeName() || '-' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">婚姻状态</text>
					<text class="value">{{ getMaritalStatusName() || '-' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">身高</text>
					<text class="value">{{ formData.height ? formData.height + ' cm' : '-' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">体重</text>
					<text class="value">{{ formData.weight ? formData.weight + ' kg' : '-' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">地区</text>
					<text class="value">{{ formData.region || '-' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">收缩压</text>
					<text class="value">{{ formData.systolic_pressure ? formData.systolic_pressure + ' mmHg' : '-' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">舒张压</text>
					<text class="value">{{ formData.diastolic_pressure ? formData.diastolic_pressure + ' mmHg' : '-' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">空腹血糖</text>
					<text class="value">{{ formData.fasting_blood_sugar ? formData.fasting_blood_sugar + ' mmol/L' : '-' }}</text>
				</view>
			</view>
			
			<!-- 现病史 -->
			<view class="section">
				<view class="section-title">现病史</view>
				
				<view class="info-item">
					<text class="label">患病年数</text>
					<text class="value">{{ formatDiabetesDiscovery(formData.diabetes_discovery_year) }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">当地诊断结果</text>
					<view class="tag-list">
						<text v-for="item in (formData.local_hospital_diagnosis || [])" :key="item" class="tag">{{ item }}</text>
						<text v-if="!formData.local_hospital_diagnosis || formData.local_hospital_diagnosis.length === 0" class="value">-</text>
					</view>
				</view>
				
				<view class="info-item">
					<text class="label">当地就诊医院</text>
					<text class="value">{{ formData.local_hospital_name || '-' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">口腔感觉</text>
					<text class="value">{{ getAppetiteName() || '-' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">每日饮水量</text>
					<text class="value">{{ getWaterIntakeName() || '-' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">体重变化</text>
					<text class="value">{{ getWeightChangeName() || '-' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">脂肪肝程度</text>
					<text class="value">{{ getFattyLiverDegreeName() || '-' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">饮食情况</text>
					<view class="tag-list">
						<text v-for="item in getDietConditionNames()" :key="item" class="tag">{{ item }}</text>
						<text v-if="getDietConditionNames().length === 0" class="value">-</text>
					</view>
				</view>
				
				<view class="info-item">
					<text class="label">肢体感觉</text>
					<view class="tag-list">
						<text v-for="item in getBodyFeelingNames()" :key="item" class="tag">{{ item }}</text>
						<text v-if="getBodyFeelingNames().length === 0" class="value">-</text>
					</view>
				</view>
				
				<view class="info-item">
					<text class="label">睡眠情况</text>
					<view class="tag-list">
						<text v-for="item in getSleepConditionNames()" :key="item" class="tag">{{ item }}</text>
						<text v-if="getSleepConditionNames().length === 0" class="value">-</text>
					</view>
				</view>
				
				<view class="info-item">
					<text class="label">眼睛情况</text>
					<view class="tag-list">
						<text v-for="item in getMultiNames(formData.eye_condition, eyeConditionOptions)" :key="item" class="tag">{{ item }}</text>
						<text v-if="getMultiNames(formData.eye_condition, eyeConditionOptions).length === 0" class="value">-</text>
					</view>
				</view>
				
				<view class="info-item">
					<text class="label">头部感觉</text>
					<view class="tag-list">
						<text v-for="item in getMultiNames(formData.head_feeling, headFeelingOptions)" :key="item" class="tag">{{ item }}</text>
						<text v-if="getMultiNames(formData.head_feeling, headFeelingOptions).length === 0" class="value">-</text>
					</view>
				</view>
				
				<view class="info-item">
					<text class="label">出汗情况</text>
					<view class="tag-list">
						<text v-for="item in getMultiNames(formData.sweat_condition, sweatConditionOptions)" :key="item" class="tag">{{ item }}</text>
						<text v-if="getMultiNames(formData.sweat_condition, sweatConditionOptions).length === 0" class="value">-</text>
					</view>
				</view>
				
				<view class="info-item">
					<text class="label">皮肤情况</text>
					<view class="tag-list">
						<text v-for="item in getMultiNames(formData.skin_condition, skinConditionOptions)" :key="item" class="tag">{{ item }}</text>
						<text v-if="getMultiNames(formData.skin_condition, skinConditionOptions).length === 0" class="value">-</text>
					</view>
				</view>
				
				<view class="info-item">
					<text class="label">小便情况</text>
					<view class="tag-list">
						<text v-for="item in getMultiNames(formData.urine_condition, urineConditionOptions)" :key="item" class="tag">{{ item }}</text>
						<text v-if="getMultiNames(formData.urine_condition, urineConditionOptions).length === 0" class="value">-</text>
					</view>
				</view>
				
				<view class="info-item">
					<text class="label">大便情况</text>
					<view class="tag-list">
						<text v-for="item in getMultiNames(formData.stool_condition, stoolConditionOptions)" :key="item" class="tag">{{ item }}</text>
						<text v-if="getMultiNames(formData.stool_condition, stoolConditionOptions).length === 0" class="value">-</text>
					</view>
				</view>
				
				<view class="info-item">
					<text class="label">腰肾情况</text>
					<view class="tag-list">
						<text v-for="item in getMultiNames(formData.kidney_condition, kidneyConditionOptions)" :key="item" class="tag">{{ item }}</text>
						<text v-if="getMultiNames(formData.kidney_condition, kidneyConditionOptions).length === 0" class="value">-</text>
					</view>
				</view>
			</view>
			
			<!-- 既往史 -->
			<view class="section">
				<view class="section-title">既往史</view>
				
				<view class="info-item">
					<text class="label">既往史</text>
					<view class="tag-list">
						<text v-for="item in getPastHistoryNames()" :key="item" class="tag">{{ item }}</text>
						<text v-if="getPastHistoryNames().length === 0" class="value">-</text>
					</view>
				</view>
			</view>
			
			<!-- 其他病史 -->
			<view class="section">
				<view class="section-title">其他病史</view>
				
				<view class="info-item">
					<text class="label">外伤史</text>
					<text class="value">{{ formData.trauma_history === 1 ? '有' : '无' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">手术史</text>
					<text class="value">{{ formData.surgery_history === 1 ? '有' : '无' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">过敏史</text>
					<text class="value">{{ formData.allergy_history === 1 ? '有' : '无' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">家族病史</text>
					<text class="value">{{ formData.family_history === 1 ? '有' : '无' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">妊娠哺乳史</text>
					<text class="value">{{ formData.pregnancy_history === 1 ? '有' : '无' }}</text>
				</view>
			</view>
			
			<!-- 诊断信息 -->
			<view class="section">
				<view class="section-title">诊断信息</view>
				
				<view class="info-item" v-if="formData.tongue_images && formData.tongue_images.length > 0">
					<text class="label">舌苔照片</text>
					<view class="image-list">
						<image 
							v-for="(img, index) in formData.tongue_images" 
							:key="index" 
							:src="img" 
							class="tongue-image"
							mode="aspectFill"
							@click="previewImage(img)"
						/>
					</view>
				</view>
				
				<view class="info-item">
					<text class="label">症状</text>
					<text class="value multi-line">{{ formData.symptoms || '-' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">舌苔</text>
					<text class="value">{{ formData.tongue_coating || '-' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">脉象</text>
					<text class="value">{{ formData.pulse || '-' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">治则</text>
					<text class="value multi-line">{{ formData.treatment_principle || '-' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">处方</text>
					<text class="value multi-line">{{ formData.prescription || '-' }}</text>
				</view>
				
				<view class="info-item">
					<text class="label">医嘱</text>
					<text class="value multi-line">{{ formData.doctor_advice || '-' }}</text>
				</view>
				
				<view class="info-item" v-if="formData.report_files && formData.report_files.length > 0">
					<text class="label">检查报告</text>
					<view class="image-list">
						<image 
							v-for="(img, index) in formData.report_files" 
							:key="index" 
							:src="img" 
							class="tongue-image"
							mode="aspectFill"
							@click="previewImage(img)"
						/>
					</view>
				</view>
				
				<view class="info-item">
					<text class="label">备注</text>
					<text class="value multi-line">{{ formData.remark || '-' }}</text>
				</view>
			</view>
			
		</view>
		
		<!-- 底部浮动按钮 -->
		<view class="fixed-bottom">
			<button class="confirm-btn" @click="handleConfirm">确认诊单</button>
		</view>
	</view>
	
	
</view>
	
</template>

<script setup>
import { ref,onMounted,getCurrentInstance  } from "vue";
import { onShow, onShareAppMessage,onLaunch } from '@dcloudio/uni-app'
// 2. 获取组件实例，通过 proxy 访问全局属性
import * as GenerateTestUserSig from "@/debug/GenerateTestUserSig-es.js";
import { CallManager } from "@/TUICallKit/src/TUICallService/serve/callManager";
const { proxy } = getCurrentInstance()

const formatDiabetesDiscovery = (v) => {
	if (v == null || v === '') return '-'
	const s = String(v).trim()
	if (s === '') return '-'
	return /^\d+$/.test(s) ? s + ' 年' : s
}

const globalData = {
	SDKAppID: 0,
	userID: '',
	userSig: ''
};
let avatarUrl = ref("");  // 声明为响应式变量
uni.CallManager = new CallManager();
const formData = ref({
	patient_name: '',
	id_card: '',
	phone: '',
	gender: 1,
	age: '',
	diagnosis_date: '',
	diagnosis_type: '',
	syndrome_type: '',
	diabetes_type: '',
	marital_status: '',
	height: '',
	weight: '',
	region: '',
	systolic_pressure: '',
	diastolic_pressure: '',
	fasting_blood_sugar: '',
	diabetes_discovery_year: '',
	local_hospital_diagnosis: [],
	local_hospital_name: '',
	appetite: '',
	water_intake: '',
	diet_condition: [],
	weight_change: '',
	body_feeling: [],
	sleep_condition: [],
	eye_condition: [],
	head_feeling: [],
	sweat_condition: [],
	skin_condition: [],
	urine_condition: [],
	stool_condition: [],
	kidney_condition: [],
	fatty_liver_degree: '',
	past_history: [],
	trauma_history: 0,
	surgery_history: 0,
	allergy_history: 0,
	family_history: 0,
	pregnancy_history: 0,
	tongue_images: [],
	report_files: [],
	symptoms: '',
	tongue_coating: '',
	pulse: '',
	treatment_principle: '',
	prescription: '',
	doctor_advice: '',
	remark: ''
});
let dingdan_ok=ref(false)
const showPatientModal = ref(false)
const confirmBtnLoading = ref(false) // 防止多次点击
// 字典选项
const diagnosisTypeOptions = ref([]);
const syndromeTypeOptions = ref([]);
const diabetesTypeOptions = ref([]);
const pastHistoryOptions = ref([]);
const appetiteOptions = ref([]);
const waterIntakeOptions = ref([]);
const dietConditionOptions = ref([]);
const weightChangeOptions = ref([]);
const bodyFeelingOptions = ref([]);
const sleepConditionOptions = ref([]);
const fattyLiverDegreeOptions = ref([]);
const eyeConditionOptions = ref([]);
const headFeelingOptions = ref([]);
const sweatConditionOptions = ref([]);
const skinConditionOptions = ref([]);
const urineConditionOptions = ref([]);
const stoolConditionOptions = ref([]);
const kidneyConditionOptions = ref([]);

onMounted(() => {
	getDictOptions();
	loadDiagnosisDetail();
});

// 获取字典数据
const getDictOptions = async () => {
	try {
		const [
			diagnosisType, 
			syndromeType,
			diabetesType,
			pastHistory,
			appetite,
			waterIntake,
			dietCondition,
			weightChange,
			bodyFeeling,
			sleepCondition,
			fattyLiverDegree,
			eyeCondition,
			headFeeling,
			sweatCondition,
			skinCondition,
			urineCondition,
			stoolCondition,
			kidneyCondition
		] = await Promise.all([
			getDictData('diagnosis_type'),
			getDictData('syndrome_type'),
			getDictData('diabetes_type'),
			getDictData('past_history'),
			getDictData('appetite'),
			getDictData('water_intake'),
			getDictData('diet_condition'),
			getDictData('weight_change'),
			getDictData('body_feeling'),
			getDictData('sleep_condition'),
			getDictData('fatty_liver_degree'),
			getDictData('eye_condition'),
			getDictData('head_feeling'),
			getDictData('sweat_condition'),
			getDictData('skin_condition'),
			getDictData('urine_condition'),
			getDictData('stool_condition'),
			getDictData('kidney_condition')
		]);
		
		diagnosisTypeOptions.value = diagnosisType?.diagnosis_type || [];
		syndromeTypeOptions.value = syndromeType?.syndrome_type || [];
		diabetesTypeOptions.value = diabetesType?.diabetes_type || [];
		pastHistoryOptions.value = pastHistory?.past_history || [];
		appetiteOptions.value = appetite?.appetite || [];
		waterIntakeOptions.value = waterIntake?.water_intake || [];
		dietConditionOptions.value = dietCondition?.diet_condition || [];
		weightChangeOptions.value = weightChange?.weight_change || [];
		bodyFeelingOptions.value = bodyFeeling?.body_feeling || [];
		sleepConditionOptions.value = sleepCondition?.sleep_condition || [];
		fattyLiverDegreeOptions.value = fattyLiverDegree?.fatty_liver_degree || [];
		eyeConditionOptions.value = eyeCondition?.eye_condition || [];
		headFeelingOptions.value = headFeeling?.head_feeling || [];
		sweatConditionOptions.value = sweatCondition?.sweat_condition || [];
		skinConditionOptions.value = skinCondition?.skin_condition || [];
		urineConditionOptions.value = urineCondition?.urine_condition || [];
		stoolConditionOptions.value = stoolCondition?.stool_condition || [];
		kidneyConditionOptions.value = kidneyCondition?.kidney_condition || [];
	} catch (error) {
		console.error('获取字典数据失败:', error);
	}
};

// 获取单个字典数据
const getDictData = async (type) => {
	try {
		const res = await proxy.apiUrl({
			url: '/api/tcm/getDict',
			method: 'GET',
			data: { type }
		}, false);
		
		if (res.code === 1) {
			return res.data;
		}
		return null;
	} catch (error) {
		console.error(`获取字典${type}失败:`, error);
		return null;
	}
};
onShareAppMessage((res) =>{
    return {
      title: '点击进入诊室',
      path: '/pages/order/monad/monad?id='+diagnosisId+'&sa='+share_user_id+'&did='+doctorId.value,
      imageUrl: '/static/zs.jpg',
      desc: '点击进入诊室',
      success() {
        uni.showToast({ title: '分享成功', icon: 'success' });
      },
      fail(err) {
        console.log('分享失败：', err);
        uni.showToast({ title: '分享失败', icon: 'none' });
      }
    }
});
let diagnosisId=''
let share_user_id='';
let doctorId=ref('');
// 加载诊单详情
const loadDiagnosisDetail = async () => {
	// 从页面参数获取诊单ID
	const pages = getCurrentPages();
	const currentPage = pages[pages.length - 1];
	const params = proxy.$parsePageParams(currentPage.options);
	dingdan_ok.value=false;
	diagnosisId = params.id;
	share_user_id = params.share_user|| params.sa;
	doctorId.value = params.doctor_id||params.did;
	console.log('进入onMounted:', params, '诊单ID:', diagnosisId, '医生ID:', doctorId);
	
	if (!diagnosisId) {
		uni.showToast({ title: '缺少诊单ID', icon: 'none' });
		return;
	}
	
	uni.showLoading({ title: '加载中...' });
	
	try {
		// 通过 proxy 调用全局的 apiUrl
		const res = await proxy.apiUrl({
			url: '/api/tcm/diagnosisDetail',
			method: 'GET',
			data: {
				id: diagnosisId,
				user_id: params.share_user_id || 0,
				share_user_id: params.share_user || 0
			},
		}, false); // 不显示加载中
		
		if (res.code === 1) {
			formData.value = res.data;
			showPatientModal.value = true; // 进入页面后直接弹窗显示就诊人信息
		} else {
			uni.showToast({ title: res.msg || '加载失败', icon: 'none' });
		}
	} catch (err) {
		uni.showToast({ title: '请求失败', icon: 'none' });
		console.error(err);
	} finally {
		uni.hideLoading();
	}
};

// 获取当地医院诊断文本（用顿号连接）
const getLocalDiagnosisText = () => {
	const val = formData.value.local_hospital_diagnosis;
	if (!val) return '-';
	if (Array.isArray(val)) {
		if (val.length === 0) return '-';
		const text = val.map(v => (typeof v === 'object' && v?.name) ? v.name : String(v)).join('、');
		return text ? text + '、' : '-';
	}
	return String(val) + '、';
};

// ---- 音视频权限辅助（仅微信小程序） ----
// #ifdef MP-WEIXIN
const requestAVPermissionsInModal = () => new Promise((resolve) => {
	const guide = (deniedScope) => {
		uni.showModal({
			title: '需要摄像头和麦克风权限',
			content: '视频问诊需要摄像头和麦克风权限，请点击「去设置」开启后重试',
			confirmText: '去设置',
			cancelText: '取消',
			success: (res) => {
				if (res.confirm) wx.openSetting();
				resolve(false);
			}
		});
	};
	wx.authorize({
		scope: 'scope.camera',
		success: () => {
			wx.authorize({
				scope: 'scope.record',
				success: () => resolve(true),
				fail: () => guide('record')
			});
		},
		fail: () => guide('camera')
	});
});
// #endif
// #ifndef MP-WEIXIN
const requestAVPermissionsInModal = () => Promise.resolve(true);
// #endif

// 关闭就诊人信息弹窗
const closePatientModal = async () => {
	if (confirmBtnLoading.value) return;
	confirmBtnLoading.value = true;
	try {
		// 在用户主动点击的时机申请摄像头 + 麦克风权限
		// （首次会弹原生授权弹窗；已拒绝则引导去设置页）
		const granted = await requestAVPermissionsInModal();
		if (!granted) return; // 未授权，停止跳转
		const app = getApp();
		// const userID = app.globalData.userID;
		// const userSig = app.globalData.userSig;
		// const SDKAppID = app.globalData.SDKAppID;
		const doctor = 'doctor_' + doctorId.value;
		await confirmDiagnosis(diagnosisId);
		if(!diagnosisId.includes('patient')){
			diagnosisId='patient_'+diagnosisId
		}
		const { userSig, SDKAppID } = GenerateTestUserSig.genTestUserSig({
		  userID:diagnosisId,
		});
		if (!doctorId.value) {
			uni.showToast({ title: '诊室号不存在，联系助理处理！', icon: 'none' });
			return;
		}
	
		console.log(app.globalData, diagnosisId);

		const url=`/TUIKit/pages/chat/chat?userID=${encodeURIComponent(diagnosisId)}&userSig=${encodeURIComponent(userSig)}&SDKAppID=${SDKAppID}&targetUserID=${doctor}&msg=1`
		
		showPatientModal.value = false;
		uni.redirectTo({
			url: url
		});
	} catch (err) {
		console.error(err);
		uni.showToast({ title: '操作失败', icon: 'none' });
	} finally {
		confirmBtnLoading.value = false;
	}
};
const video =async (data)=>{
	const res = await proxy.apiUrl({
	  url: '/api/tcm/getPatientSignature',
	  method: 'GET',
	  data: {
	     patient_id:diagnosisId
	  },
	}, false) 
	
	const {userId } = res.data;
	
	const { userSig, SDKAppID } = GenerateTestUserSig.genTestUserSig({
	  userID:userId,
	});
		
	getApp().globalData.userID = userId;
	getApp().globalData.userSig = userSig;
	getApp().globalData.SDKAppID = SDKAppID;
	const cc={
	  sdkAppID: SDKAppID, // 替换为用户自己的 sdkAppID
	  userID: userId, // 替换为用户自己的 userID
	  userSig: userSig, // 替换为用户自己的 userSig
	  globalCallPagePath: "TUICallKit/src/Components/TUICallKit", // 替换为步骤一里注册的全局监听页面
	}
	uni.setStorageSync('CallManager', userId)
	await uni.CallManager.init(cc);
}
// 打开知情同意书
const openConsentForm = () => {
	// 可跳转到知情同意书页面，或使用 web-view 打开外部链接
	uni.navigateTo({
		url: '/pages/Card/contact?type=service'
	})
};

// 获取选中项名称
const getDiagnosisTypeName = () => {
	const item = diagnosisTypeOptions.value.find(i => i.value === formData.value.diagnosis_type);
	return item ? item.name : '';
};

const getSyndromeTypeName = () => {
	const item = syndromeTypeOptions.value.find(i => i.value === formData.value.syndrome_type);
	return item ? item.name : '';
};

const getDiabetesTypeName = () => {
	const item = diabetesTypeOptions.value.find(i => i.value === formData.value.diabetes_type);
	return item ? item.name : '';
};

const getAppetiteName = () => {
	const item = appetiteOptions.value.find(i => i.value === formData.value.appetite);
	return item ? item.name : '';
};

const getWaterIntakeName = () => {
	const item = waterIntakeOptions.value.find(i => i.value === formData.value.water_intake);
	return item ? item.name : '';
};

const getWeightChangeName = () => {
	const item = weightChangeOptions.value.find(i => i.value === formData.value.weight_change);
	return item ? item.name : '';
};

const getFattyLiverDegreeName = () => {
	const item = fattyLiverDegreeOptions.value.find(i => i.value === formData.value.fatty_liver_degree);
	return item ? item.name : '';
};

const getDietConditionNames = () => {
	if (!formData.value.diet_condition || formData.value.diet_condition.length === 0) return [];
	// 处理字符串类型（逗号分隔）或数组类型
	const values = Array.isArray(formData.value.diet_condition) 
		? formData.value.diet_condition 
		: formData.value.diet_condition.split(',');
	
	return values.map(val => {
		const item = dietConditionOptions.value.find(i => i.value === val);
		return item ? item.name : val;
	}).filter(Boolean);
};

const getBodyFeelingNames = () => {
	if (!formData.value.body_feeling || formData.value.body_feeling.length === 0) return [];
	// 处理字符串类型（逗号分隔）或数组类型
	const values = Array.isArray(formData.value.body_feeling) 
		? formData.value.body_feeling 
		: formData.value.body_feeling.split(',');
	
	return values.map(val => {
		const item = bodyFeelingOptions.value.find(i => i.value === val);
		return item ? item.name : val;
	}).filter(Boolean);
};

const getSleepConditionNames = () => {
	if (!formData.value.sleep_condition || formData.value.sleep_condition.length === 0) return [];
	// 处理字符串类型（逗号分隔）或数组类型
	const values = Array.isArray(formData.value.sleep_condition) 
		? formData.value.sleep_condition 
		: formData.value.sleep_condition.split(',');
	
	return values.map(val => {
		const item = sleepConditionOptions.value.find(i => i.value === val);
		return item ? item.name : val;
	}).filter(Boolean);
};

const getPastHistoryNames = () => {
	if (!formData.value.past_history || formData.value.past_history.length === 0) return [];
	const values = Array.isArray(formData.value.past_history) 
		? formData.value.past_history 
		: formData.value.past_history.split(',');
	return values.map(val => {
		const item = pastHistoryOptions.value.find(i => i.value === val);
		return item ? item.name : val;
	}).filter(Boolean);
};

// 通用多选名称获取
const getMultiNames = (fieldValues, options) => {
	if (!fieldValues || fieldValues.length === 0) return [];
	const values = Array.isArray(fieldValues) ? fieldValues : fieldValues.split(',');
	return values.map(val => {
		const item = options.find(i => i.value === val);
		return item ? item.name : val;
	}).filter(Boolean);
};

const getMaritalStatusName = () => {
	const map = { 0: '未婚', 1: '已婚', 2: '离异' };
	const v = formData.value.marital_status;
	return (v !== '' && v !== undefined && v !== null) ? (map[v] || '-') : '';
};

// 预览图片
const previewImage = (current) => {
	uni.previewImage({
		current,
		urls: formData.value.tongue_images
	});
};

// 确认诊单
const handleConfirm = () => {
	uni.showModal({
		title: '确认诊单',
		content: '确认后将无法修改，是否确认？',
		success: (res) => {
			if (res.confirm) {
				confirmDiagnosis();
			}
		}
	});
};

// 提交确认诊单
const confirmDiagnosis = async (diagnosisId) => {
	
	
	console.log('确认诊单参数:', diagnosisId);
	
	if (!diagnosisId) {
		uni.showToast({ title: '缺少诊单ID', icon: 'none' });
		return;
	}



	
	const app = getApp();
	
	try {
		const res = await proxy.apiUrl({
			url: '/api/tcm/confirmDiagnosis',
			method: 'POST',
			data: {
				id: diagnosisId,
				share_user: share_user_id || 0
			}
		}, false);
		
		if (res.code === 1) {
		
			
			 uni.setStorageSync('dingdan_ok', true);
		
		
		} else {
			uni.showToast({ title: res.msg || '确认失败', icon: 'none' });
		}
	} catch (err) {
		uni.showToast({ title: '请求失败', icon: 'none' });
		console.error(err);
	} finally {
		uni.hideLoading();
	}
};
</script>

<style lang="scss">
.container {
	min-height: 100vh;
	background-color: #f0f0f0;
}

.form-wrapper {
	padding: 24rpx;
	padding-bottom: 180rpx; /* 为底部按钮留出空间 */
}

.section {
	background-color: #fff;
	border-radius: 20rpx;
	padding: 40rpx;
	margin-bottom: 24rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
}

.section-title {
	font-size: 40rpx; /* 大字体，老年人易读 */
	font-weight: bold;
	color: #1a1a1a;
	margin-bottom: 36rpx;
	padding-bottom: 24rpx;
	border-bottom: 3rpx solid #e0e0e0;
	letter-spacing: 2rpx;
}

.info-item {
	display: flex;
	align-items: flex-start;
	margin-bottom: 36rpx; /* 加大行间距，减少视觉拥挤 */
	line-height: 1.8;
	
	&:last-child {
		margin-bottom: 0;
	}
}

.label {
	flex-shrink: 0;
	width: 200rpx;
	font-size: 34rpx; /* 放大标签字体 */
	color: #555;
	font-weight: 600;
	padding-top: 2rpx;
}

.value {
	flex: 1;
	font-size: 34rpx; /* 放大内容字体 */
	color: #111; /* 深色，高对比度 */
	word-break: break-all;
	line-height: 1.8;
	
	&.multi-line {
		white-space: pre-wrap;
		line-height: 2.0;
	}
}

.tag-list {
	flex: 1;
	display: flex;
	flex-wrap: wrap;
	gap: 20rpx;
}

.tag {
	display: inline-block;
	padding: 12rpx 28rpx; /* 更大的点击区域 */
	background-color: #e8f4ff;
	color: #0066cc; /* 深蓝，对比度更高 */
	font-size: 32rpx; /* 标签字体也放大 */
	font-weight: 500;
	border-radius: 10rpx;
	border: 1rpx solid #b3d9ff;
}

.image-list {
	flex: 1;
	display: flex;
	flex-wrap: wrap;
	gap: 24rpx;
}

.tongue-image {
	width: 220rpx;
	height: 220rpx;
	border-radius: 12rpx;
	border: 2rpx solid #e0e0e0;
}

.fixed-bottom {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	padding: 24rpx 40rpx;
	padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
	background: linear-gradient(to top, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 0.95) 80%, rgba(255, 255, 255, 0) 100%);
	z-index: 100;
}

.confirm-btn {
	width: 100%;
	height: 110rpx; /* 更高的按钮，老年人更容易点击 */
	background: linear-gradient(135deg, #2e7d32 0%, #43a047 100%); /* 绿色，更直观 */
	color: #fff;
	font-size: 40rpx; /* 按钮字体放大 */
	font-weight: bold;
	border-radius: 55rpx;
	border: none;
	box-shadow: 0 8rpx 24rpx rgba(46, 125, 50, 0.35);
	letter-spacing: 4rpx;
}

/* 确认成功页面样式 */
.success-container {
	min-height: 100vh;
	display: flex;
	align-items: center;
	justify-content: center;
	background: linear-gradient(135deg, #2e7d32 0%, #43a047 100%);
	padding: 40rpx;
}

.success-content {
	width: 100%;
	max-width: 620rpx;
	background: #fff;
	border-radius: 32rpx;
	padding: 90rpx 50rpx 70rpx;
	text-align: center;
	box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.15);
	animation: successFadeIn 0.5s ease-out;
}

@keyframes successFadeIn {
	from {
		opacity: 0;
		transform: translateY(-40rpx);
	}
	to {
		opacity: 1;
		transform: translateY(0);
	}
}

.success-icon-wrapper {
	margin-bottom: 48rpx;
}

.success-icon-circle {
	width: 180rpx;
	height: 180rpx;
	margin: 0 auto;
	background: linear-gradient(135deg, #2e7d32 0%, #66bb6a 100%);
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 12rpx 40rpx rgba(46, 125, 50, 0.35);
	animation: successScale 0.6s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}

@keyframes successScale {
	0% {
		transform: scale(0);
		opacity: 0;
	}
	50% {
		transform: scale(1.1);
	}
	100% {
		transform: scale(1);
		opacity: 1;
	}
}

.success-icon-check {
	font-size: 110rpx;
	color: #fff;
	font-weight: bold;
	line-height: 1;
}

.success-title {
	font-size: 56rpx; /* 成功标题大字 */
	font-weight: bold;
	color: #1a1a1a;
	margin-bottom: 28rpx;
	animation: successSlideIn 0.6s ease-out 0.2s both;
	letter-spacing: 4rpx;
}

@keyframes successSlideIn {
	from {
		opacity: 0;
		transform: translateY(20rpx);
	}
	to {
		opacity: 1;
		transform: translateY(0);
	}
}

.success-message {
	font-size: 36rpx; /* 提示文字也放大 */
	color: #444;
	line-height: 1.8;
	margin-bottom: 16rpx;
	animation: successSlideIn 0.6s ease-out 0.3s both;
}

.success-tips {
	font-size: 30rpx;
	color: #777;
	animation: successSlideIn 0.6s ease-out 0.4s both;
}

/* 就诊人信息弹窗 */
.modal-overlay {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: #000;
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 999;
	padding: 40rpx;
}

.patient-modal {
	width: 100%;
	max-width: 620rpx;
	background: #fff;
	border-radius: 24rpx;
	padding: 48rpx 40rpx 40rpx;
	box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.2);
}

.modal-title {
	font-size: 40rpx;
	font-weight: bold;
	color: #1a1a1a;
	text-align: center;
	margin-bottom: 32rpx;
}

.patient-info-box {
	background: #f5f5f5;
	border: 2rpx solid #e8e8e8;
	border-radius: 16rpx;
	padding: 28rpx 32rpx;
	margin-bottom: 32rpx;
}

.info-row {
	font-size: 35rpx;
	color: #333;
	line-height: 2;
	text-align: left;
}

.agreement-row {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 32rpx;
	line-height: 1.8;
}

.agreement-link {
	color: #1890ff;
	text-decoration: underline;
}

.modal-confirm-btn {
	width: 100%;
	height: 96rpx;
	line-height: 96rpx;
	background: #00C853;
	color: #fff;
	font-size: 34rpx;
	font-weight: 500;
	border-radius: 48rpx;
	border: none;
}
</style>
