<template>
	<view class="consult-detail-page">
		<!-- 导航栏 -->
        <navBar title="咨询详情" />

		<!-- 内容区域 -->
		<scroll-view scroll-y class="content-scroll">
			<!-- 用户信息区域 -->
			<view class="user-section">
				<view class="user-info">
					<image v-if="userInfo.avatar" :src="userInfo.avatar" class="user-avatar" mode="aspectFill" />
					<view class="user-details">
						<view class="user-name">
							<text class="name">{{ userInfo.name }}</text>
							<text class="gender-age" v-if="userInfo.gender !== '未知'">（{{ userInfo.gender }} {{ userInfo.age }}岁）</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 疾病标签和日期 -->
			<view class="tag-date-row">
				<view class="disease-tag">
					<text class="tag-text">{{ questionInfo.diseaseTag }}</text>
				</view>
				<view class="date">{{ questionInfo.date }}</view>
			</view>

			<!-- 问题内容 -->
			<view class="question-content">
				<text class="content-text">{{ questionInfo.diseaseDescribe }}</text>
			</view>

			<!-- 疾病描述 -->
			<!-- <view v-if="questionInfo.diseaseDescribe" class="disease-describe">
				<view class="describe-title">疾病描述：</view>
				<text class="describe-text">{{ questionInfo.diseaseDescribe }}</text>
			</view> -->

			<!-- 图片网格 -->
			<view class="image-grid" v-if="questionInfo.images && questionInfo.images.length > 0">
				<image 
					v-for="(img, index) in questionInfo.images" 
					:key="index"
					:src="docUrl+img.path"
					class="grid-image"
					mode="aspectFill"
					@click="previewImage(docUrl+img.path, index)"
				/>
			</view>
            <view class="bar"></view>


		</scroll-view>

		<!-- 底部固定区域 -->
		<view class="bottom-fixed">
			<!-- 特别声明 -->
			<!-- 编辑按钮 -->
			<view class="edit-btn" @click="answerConsult">
				我要回答
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref } from 'vue'
import navBar from '@/components/navBar/navBar.vue'
import detailImg from "@/static/iv_jiwangshi.png"
import navTo from '@/utils/navTo.js'
import { onLoad,onShow } from '@dcloudio/uni-app'
import docUrl from '@/utils/docUrl'
import api  from "@/api/api.js"
const uuid = ref('');
const step1_uuid = ref('');
let patientUuid = ref('');
const status = ref(0);
const hasAnswer = ref(false);
onLoad((options) => {
	uuid.value = options.uuid 
	status.value = options.status || 0
	
})

const consultDetail=()=>{
  api.consultDetail({
	uuid:uuid.value
  }).then(res=>{
	console.log('咨询详情数据:', res)
	if(res.code === 200 && res.data && res.data.detail) {
		const detail = res.data.detail
        patientUuid.value = detail.patientUuid;
		// 更新用户信息
		userInfo.value = {
			name: detail.patientName ,
			gender: '未知', // 新数据结构中没有性别信息
			age: '未知' // 新数据结构中没有年龄信息
		}
		
		// 更新问题信息
		questionInfo.value = {
			date: detail.createDate ? formatDate(detail.createDate) : '未知',
			diseaseTag: detail.diseaseName || '未知疾病',
			content: detail.content || '暂无问题描述',
			images: res.data.imgList?res.data.imgList:[],
			your_question: detail.content || '',
			diseaseDescribe: detail.content || '' // 将咨询内容作为疾病描述显示
		}
		
		// 更新患者头像
		if(detail.patientPhoto) {
			userInfo.value.avatar = docUrl + detail.patientPhoto
		}
		
		// 更新状态信息
		status.value = detail.state || 0
		
		console.log('更新后的用户信息:', userInfo.value)
		console.log('更新后的问题信息:', questionInfo.value)
	} else {
		console.error('获取咨询详情失败:', res)
		uni.showToast({
			title: res.msg || '获取咨询详情失败',
			icon: 'none'
		})
	}
  }).catch(err => {
	console.error('请求咨询详情失败:', err)
	uni.showToast({
		title: '网络请求失败',
		icon: 'none'
	})
  })
}
const countConsult=()=>{
	api.countConsult({
		consultUuid:uuid.value,
        expertUuid:uni.getStorageSync('userInfo').uuid
	}).then(res=>{
        console.log('咨询数量:', res)
		if(res.code ==200 && res.data){
			if(res.data> 0){
				uni.showModal({
					title: '提示',
					content: `您已回答过该患者${res.data}次公益咨询，是否确定回答`,
					success: (res)=>{
						if(res.confirm){
							resConsult()
						}
					}
				})
			}else{
				resConsult();
			}
		}
	})
}
const answerConsult=async()=>{
    if(hasAnswer.value){
        let userId=uni.getStorageSync('userInfo').uuid.toLowerCase();
		    let conversationId=userId+'|1|'+patientUuid.value.toLowerCase();
	       await uni.$UIKitStore.uiStore.selectConversation(conversationId)
            navTo({
                    url:'/pages_chat/chat/index?from=consult&patientUuid='+patientUuid.value
                })
    }else{
        countConsult()
    }
	
}

const resConsult=()=>{
	api.resConsult({
		consultUuid:uuid.value,
        expertUuid:uni.getStorageSync('userInfo').uuid
	}).then(async(res)=>{
		if(res.code ==200){
            hasAnswer.value = true;
            patientUuid.value = res.data.patient_uuid;
            let userId=uni.getStorageSync('userInfo').uuid.toLowerCase();
		    let conversationId=userId+'|1|'+patientUuid.value.toLowerCase();
	       await uni.$UIKitStore.uiStore.selectConversation(conversationId)
            navTo({
                    url:'/pages_chat/chat/index?from=consult&patientUuid='+patientUuid.value+'&uuid='+uuid.value
                })
                }
	})
}
onShow(()=>{
	consultDetail()
})

// 计算年龄
function calculateAge(birthday) {
	const birthDate = new Date(birthday)
	const today = new Date()
	let age = today.getFullYear() - birthDate.getFullYear()
	const monthDiff = today.getMonth() - birthDate.getMonth()
	if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
		age--
	}
	return age.toString()
}

// 格式化日期
function formatDate(dateString) {
	const date = new Date(dateString)
	const year = date.getFullYear()
	const month = String(date.getMonth() + 1).padStart(2, '0')
	const day = String(date.getDate()).padStart(2, '0')
	return `${year}-${month}-${day}`
}
// 用户信息
const userInfo = ref({
	name: '提**',
	gender: '未知',
	age: '未知',
	avatar: ''
})

// 问题信息
const questionInfo = ref({
	date: '2022-11-09',
	diseaseTag: '甲型肝炎',
	content: '为什么程序员总是分不清万圣节和圣诞节？因为Oct31==Dec25。\n任何我写的代码，超过6个月不去看它，当我再看时，都像是别人写的。',
	diseaseDescribe: '', // 疾病描述
	images: [
		'/static/images/placeholder1.jpg',
		'/static/images/placeholder2.jpg',
		'/static/images/placeholder3.jpg',
		'/static/images/placeholder4.jpg',
		'/static/images/placeholder5.jpg',
		'/static/images/placeholder6.jpg',
		'/static/images/placeholder7.jpg',
		'/static/images/placeholder8.jpg'
	]
})


// 返回上一页
function goBack() {
	uni.navigateBack()
}

// 预览图片
function previewImage(current, index) {
	uni.previewImage({
		urls: questionInfo.value.images?questionInfo.value.images.map(item=> docUrl + item.path):[],
		current: index
	})
}


// 编辑问题
function editQuestion() {
	navTo({
		url:'/pages_app/myAnswer/myAnswer?uuid='+uuid.value
	})
}
</script>

<style lang="scss" scoped>
.consult-detail-page {
	background-color: #fff;
	height: 100vh;
	display: flex;
	flex-direction: column;
}

.nav-bar {
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 88rpx;
	padding: 0 32rpx;
	background-color: #ffffff;
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 100;
	
	.nav-left {
		width: 80rpx;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		
		.back-icon {
			font-size: 48rpx;
			color: #8B2316;
			font-weight: bold;
		}
	}
	
	.nav-title {
		font-size: 36rpx;
		font-weight: 500;
		color: #8B2316;
	}
	
	.nav-right {
		width: 80rpx;
	}
}
.bar{
    width:100%;
    height:20rpx;
    background-color: #efefef;
}
.content-scroll {
	flex: 1;
    position: fixed;
	top: 135rpx;
    box-sizing: border-box;
	padding: 30rpx 0;
	bottom: 100rpx;
}

.user-section {
	background-color: #ffffff;
	border-radius: 16rpx;
	margin-bottom: 24rpx;
	padding: 0 30rpx;
	.user-info {
		display: flex;
		align-items: center;
		margin-bottom: 16rpx;
		
		.user-avatar {
			width: 80rpx;
			height: 80rpx;
			border-radius: 40rpx;
			margin-right: 24rpx;
			background-color: #f0f0f0;
		}
		
		.user-details {
			flex: 1;
			
			.user-name {
				display: flex;
				align-items: center;
				margin-bottom: 8rpx;
				
				.name {
					font-size: 32rpx;
					color: #8B2316;
					font-weight: 500;
				}
				
				.gender-age {
					font-size: 28rpx;
					color: #666;
					margin-left: 8rpx;
				}
			}
			
			.user-status {
				.status-text {
					font-size: 24rpx;
					color: #999;
					padding: 4rpx 12rpx;
					background-color: #f0f0f0;
					border-radius: 12rpx;
				}
			}
		}
		
		.detail-btn {
			display: flex;
			margin-left: 10rpx;
		
			
			.detail-text {
				color: #ffffff;
				font-size: 24rpx;
				margin-right: 8rpx;
			}
			
			.detail-icon {
				color: #ffffff;
				font-size: 24rpx;
			}
		}
	}
	
}

.tag-date-row {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 24rpx;
    margin: 0 30rpx 30rpx;
	.disease-tag {
		margin-bottom: 0;
		
		.tag-text {
			display: inline-block;
			background-color: #ffffff;
			color: #8B2316;
			border: 2rpx solid #8B2316;
			border-radius: 40rpx;
			padding: 7rpx 22rpx;
			font-size: 24rpx;
		}
	}
	
	.date {
		font-size: 28rpx;
		color: #999;
	}
}

.question-content {
	background-color: #f0f0f0;
	border-radius: 16rpx;
	padding: 32rpx;
    margin: 0 30rpx;
	margin-bottom: 24rpx;
	
	.content-text {
		 font-size: 28rpx;
		color: #333;
		line-height: 1.6;
	}
}

.disease-describe {
	background-color: #f8f9fa;
	border-radius: 16rpx;
	padding: 32rpx;
	margin: 0 30rpx 24rpx;
	border-left: 6rpx solid #8B2316;
	
	.describe-title {
		font-size: 30rpx;
		color: #8B2316;
		font-weight: 500;
		margin-bottom: 16rpx;
	}
	
	.describe-text {
		font-size: 28rpx;
		color: #333;
		line-height: 1.6;
	}
}

.image-grid {
	display: grid;
	grid-template-columns: repeat(4, 1fr);
	gap: 8rpx;
    margin: 0 30rpx 40rpx;
	
	
	.grid-image {
		width: 100%;
		height: 160rpx;
		border-radius: 8rpx;
	}
}


.bottom-fixed {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	
	padding: 24rpx 32rpx;
	
}

.disclaimer {
	background-color: #fff5f5;
	border-radius: 16rpx;
	padding: 24rpx;
	margin-bottom: 24rpx;
	
	.disclaimer-title {
		font-size: 28rpx;
		color: #8B2316;
		font-weight: 500;
	}
	
	.disclaimer-text {
		font-size: 28rpx;
		color: #666;
		line-height: 1.5;
	}
}

.edit-btn {
	width: 100%;
	height: 88rpx;
	line-height: 88rpx;
	text-align: center;
    border: 1rpx solid #8B2316;
	background-color: #fff;
	color: #8B2316;
	font-size: 32rpx;
	border-radius: 16rpx;
}
</style>
