<template>
	<view class="container safe-area-inset-bottom">
		<MessageNotification />
		<!-- 预约信息 -->
		<view class="title">
			预约信息
		</view>

		<view class="card">
			<view class="item">
				<view class="aapoint">
					预约诊所
				</view>
				<view class="detail">
					{{registList.store}}
				</view>
			</view>
			<view class="item">
				<view class="aapoint">
					预约科室
				</view>
				<view class="detail">
					{{registList.depart}}
				</view>
			</view>
			<view class="item">
				<view class="aapoint">
					预约医生
				</view>
				<view class="detail">
					{{registList.doctor}}
				</view>
			</view>
			<view class="item">
				<view class="aapoint">
					预约序号
				</view>
				<view class="detail">
					{{registList.order_number}}号
				</view>
			</view>
			<view class="item">
				<view class="aapoint">
					预计就诊时间
				</view>
				<view class="detail">
					{{registList.created_at}}
				</view>
			</view>
			<view class="item">
				<view class="aapoint">
					挂号金额
				</view>
				<view class="detail active">
					{{registList.price}}元
				</view>
			</view>
			<view class="item">
				<view class="aapoint">
					挂号类型
				</view>
				<view class="detail">
          {{registerType}}
				</view>
			</view>
		</view>

		<!-- 就诊人 -->
		<view class="title">
			就诊人
		</view>

		<view class="info">
			<view class="name_edit">
				<view class="name">
					{{registList.patient}}
				</view>
				<view class="word_num">
					{{registList.order_number}}号
				</view>
			</view>

			<!-- replace(/(\w{6})\w*(\w{4})/,'$1********$2') -->
			<view class="name_edit">
				<view class="name">
					身份证号
				</view>
				<view class="word_num" v-if="registList.idcard">
					{{registList.idcard.replace(/(\w{6})\w*(\w{4})/,'$1********$2')}}
				</view>
			</view>
			<view class="name_edit">
				<view class="name">
					手机号
				</view>
				<view class="word_num" v-if="registList.mobile">
					{{registList.mobile.replace(/(\d{3})\d*(\d{4})/, '$1****$2')}}
				</view>
			</view>
		</view>

		<!-- 须知 -->
		<u-popup v-model="show" :safe-area-inset-bottom="true" mode="bottom" height="68%" border-radius="20"
			:closeable="true">
			<view class="agreen">
				<u-parse :html="content"></u-parse>
			</view>
		</u-popup>

		<!-- 底部 -->
		<view class="footer">
			<block v-if="registList.is_pay==0">
				<!-- 须知 -->
				<view class="allknow">
					<u-icon size="40" :color="form['check']?'#2979FF':'#999999'" name="checkmark-circle-fill"
						@click="form['check']=!form['check']"></u-icon>
					<view class="isknow">我已阅读并同意 <text @click="show=true">《预约挂号须知》</text> </view>
				</view>

				<!-- 按钮 -->
				<button class="btn" @click="next" :class="form['check']?'':'bg'" :disabled="!form['check']">确认挂号
				</button>
			</block>
			<view class="gh_" v-if="registList.is_pay==1" @click="toHome">
				<button class="btn">您已挂号成功，请等待医生接诊
				</button>
			</view>
		</view>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	import {
		registeInfo,
		registePay,
		registe,
		service
	} from '../../request/api/api';
  import {createRoomByDoctorIdApi, sendToUserApi} from "@/request/api/im";
  import {checkDev} from "@/utils/utils";
  import {genOrderApi, saveRegisterInfoApi} from "@/request/api/order";
  import request from "@/request/api/request";
	export default {
		data() {
			return {
				show: false,
				know: "",
				form: {
					check: false
				},
				register_id: "",
        currentUserId: "",
        currentDoctorId: "",
				registList: [],
				content: `预约挂号须知`,
				flag: true,
        registerType: '线下就诊',
        registerMap: {
          0: '挂号',
          1: '咨询',
          2: '购药',
          3: '复诊',
        },
        rInfo: {},
			}
		},
		onLoad(e) {
			// console.log(e, 'role');
      this.currentUserId = 'user-' + uni.getStorageSync('user_id') || 'user-2512';
			
			// 原有逻辑：已有 register_id
			this.register_id = e.id;
			this.rInfo = e.r_info ? (typeof e.r_info === 'string' ? JSON.parse(decodeURIComponent(e.r_info)) : e.r_info) : {};
			// 修复：如果 doctor_id 为空字符串，也使用默认值；如果 doctor_id 存在且不为空，则使用它
			const doctorId = e.doctor_id && e.doctor_id.trim() !== '' ? e.doctor_id : null;
			this.currentDoctorId = doctorId ? ('doctor-' + doctorId.replace('doctor-', '')) : 'doctor-39';
			uni.setStorageSync('register_id', this.register_id);
			
			// 获取挂号信息
			if (this.register_id) {
				this.getInfo();
			}
		},
		methods: {
			// 挂号信息
			getInfo() {
        let that = this;
				registeInfo({
					method: "post",
					data: {
						store_id: uni.getStorageSync('store_id') || '11001',
						register_id: that.register_id
					}
				}).then((res) => {
					// console.log(res, 'gh');
					if (res.data.errcode == 0) {
						that.registList = res.data.data.list[0]
            that.registerType = that.registerMap[that.registList.register_type];
						// 如果挂号信息中有医生ID，更新 currentDoctorId
						if (that.registList.service_user_id) {
							that.currentDoctorId = 'doctor-' + that.registList.service_user_id;
						}
					}
				})
			},
			// 处理在线复诊支付后的流程
			async handleOnlineConsultationAfterPayment() {
				let that = this;
				try {
					// 1. 获取医生ID（优先从挂号信息中获取，否则从 currentDoctorId 中提取）
					let doctorId = '';
					if (that.registList && that.registList.service_user_id) {
						doctorId = String(that.registList.service_user_id);
					} else {
						doctorId = that.currentDoctorId.replace('doctor-', '');
					}
					
					// 如果医生ID仍然为空，报错
					if (!doctorId || doctorId === '') {
						uni.hideLoading();
						uni.showToast({
							title: '医生ID不能为空：' + doctorId,
							icon: 'none'
						});
						return;
					}
					
					// 2. 获取患者ID
					const patientId = that.currentUserId.replace('user-', '');
					
					// 3. 创建或获取聊天房间
					// type=2 表示诊所在线复诊，type=3 表示药店在线复诊/购药
					const roomType = (that.registList && that.registList.register_type === 2) ? 2 : 3;
					const roomRes = await request('/xkApi/online-consultation/get-or-create-chat-room', {
						method: 'POST',
						data: {
							doctor_id: doctorId,
							patient_id: patientId,
							type: roomType
						}
					}, 1);
					
					const roomId = roomRes.data?.result?.room_id || roomRes.data?.room_id;
					if (!roomId) {
						uni.hideLoading();
						uni.showToast({
							title: '创建聊天房间失败',
							icon: 'none'
						});
						return;
					}
					
					// 4. 仅药店模式(store_type='1')发送患者就诊经历卡片
					const storeType = uni.getStorageSync('store_type')
					if (storeType === '1' || storeType === 1) {
						const patientExperienceData = {
							symptom_description: that.rInfo.illness_info || '',
							has_visited: that.rInfo.has_visited || '0',
							has_used_drug: that.rInfo.has_used_drug || '0',
							drug_name: that.rInfo.drug_name || '',
							illness_info: that.rInfo.illness_info || '',
							doctor_id: doctorId,
							user_id: patientId,
							register_id: that.register_id,
							created_at: new Date().toLocaleString('zh-CN')
						};
						
						// 5. 发送患者就诊经历消息（消息类型11）
						await sendToUserApi({
							room_id: roomId,
							sender_user_id: `user-${patientId}`,
							receiver_user_id: `doctor-${doctorId}`,
							message_type: 11, // 患者就诊经历卡片
							message_content: JSON.stringify(patientExperienceData),
							duration: 0
						});
					} else {
						// 诊所模式(store_type='0')发送挂号信息卡片（message_type=10）
						await sendToUserApi({
							room_id: roomId,
							sender_user_id: `user-${patientId}`,
							receiver_user_id: `doctor-${doctorId}`,
							message_type: 10, // 挂号信息卡片
							message_content: JSON.stringify({
								id: that.register_id,
							}),
							duration: 0
						});
					}
					
					// 6. 生成订单（如果需要）
					genOrderApi({
						register_id: that.register_id,
						register_info: typeof that.rInfo === 'string' ? that.rInfo : JSON.stringify(that.rInfo),
					}).then((resOrder) => {
						uni.hideLoading();
						// 跳转到聊天页面
						uni.navigateTo({
							url: `/subPackages/chat/chat?user_id=${that.currentDoctorId}&room_id=${roomId}&register_id=${that.register_id}`
						});
					}).catch((error) => {
						console.error('生成订单失败:', error);
						uni.hideLoading();
						// 即使生成订单失败，也跳转到聊天页面
						uni.navigateTo({
							url: `/subPackages/chat/chat?user_id=${that.currentDoctorId}&room_id=${roomId}&register_id=${that.register_id}`
						});
					});
				} catch (error) {
					uni.hideLoading();
					console.error('处理在线复诊流程失败:', error);
					uni.showToast({
						title: '处理失败，请重试',
						icon: 'none'
					});
				}
			},
			// 确认挂号
			next() {

				let that = this
				if (this.flag) {
					this.flag = false
					// 获取支付配置
					registePay({
						method: "post",
						data: {
							register_id: this.register_id,
							store_id: uni.getStorageSync('store_id') || '11001',
						}
					}).then((res) => {
						// console.log(res, 'pay');
						uni.showLoading({
							title: "加载中"
						});
            console.log(checkDev('open-im') && that.registList.register_type === 1, 'sssssssssssss')

            if (checkDev('open-im') && that.registList.register_type === 1) {
              // 在线咨询：创建type=1的房间
              createRoomByDoctorIdApi({
                doctor_id: that.currentDoctorId,
                type: 1 // 在线咨询
              }).then(result => {
                sendToUserApi({
                  room_id: result.data.result.room_id,
                  sender_user_id: `user-${that.currentUserId}`,
                  receiver_user_id: `doctor-${that.currentDoctorId}`,
                  message_type: 10,
                  message_content: JSON.stringify({
                    id: that.register_id,
                  }),
                  duration: 0
                })
              })
            }

						if (res.data.data.is_paid == 1) {

              if (that.registList.register_type === 2 || that.registList.register_type === 3) {
                // 在线复诊/购药流程：创建type=3的聊天房间并发送患者就诊经历消息
                that.handleOnlineConsultationAfterPayment();
                return;
              }
							setTimeout(() => {
								uni.navigateTo({
									url: `/subPackages/register/register-success?id=${that.register_id}&register_type=${that.registList.register_type}`,
								})
								uni.hideLoading();
							}, 800)

							return
						}

						uni.requestPayment({
							provider: res.data.data.appId,
							timeStamp: res.data.data.timestamp,
							nonceStr: res.data.data.nonceStr,
							package: res.data.data.package,
							signType: res.data.data.signType,
							paySign: res.data.data.paySign,
							success: (res) => {
								// console.log('success:' + JSON.stringify(res));
								setTimeout(() => {
									that.flag = false

									uni.navigateTo({
										url: '/subPackages/register/register-success?id=' +
											this.register_id
									})
									uni.hideLoading();
								}, 300)
							},
							fail: function(err) {
								// console.log('fail:' + JSON.stringify(err));
								that.flag = false
								uni.hideLoading();
								setTimeout(() => {
									that.$refs.uToast.show({
										title: res.data.msg || '支付失败',
										type: 'default',
										icon: false
									})
								}, 300)
							}
						})
					})
				}
			},
			toHome() {
				uni.switchTab({
					url: '/pages/home/home'
				})
			},
			// 预约挂号须知
			toAbout() {
				service({
					method: "get",
					data: {
						store_id: uni.getStorageSync('store_id') || '11001',
						type: 3
					}
				}).then((res) => {
					// console.log(res, 'gh');
					if (res.data.errcode == 0) {
						this.content = res.data.data.content
					}
				})
			}
		},
		mounted() {
			this.getInfo();
			this.toAbout()
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		width: 750rpx;
		max-height: 100%;
		min-height: 100vh;
		padding-top: 32rpx;
		background: #F8FAFC;

		.title {
			width: 750rpx;
			height: 80rpx;
			margin: 0 auto;
			font-size: 32rpx;
			font-family: PingFang SC-Bold, PingFang SC;
			font-weight: bold;
			color: #666666;
			line-height: 80rpx;
			padding-left: 32rpx;
		}

		.card {
			width: 750rpx;
			background: #FFFFFF;
			border-radius: 8rpx;
			padding: 32rpx;
			margin: 24rpx auto 32rpx;

			.item:first-child {
				margin: 0 0 48rpx;
			}

			.item {
				display: flex;
				justify-content: space-between;
				height: 40rpx;
				font-family: PingFang SC-Regular, PingFang SC;
				line-height: 33rpx;
				margin: 48rpx 0 0;

				.aapoint {
					font-size: 28rpx;
					font-weight: 400;
					color: #666666;
				}

				.detail {
					font-size: 28rpx;
					font-weight: bold;
					color: #232323;
				}

				.active {
					color: #F44336;
				}
			}
		}

		.info {
			width: 750rpx;
			background: #FFFFFF;
			padding: 32rpx;
			border-radius: 8rpx;
			margin: 10rpx auto 40rpx;

			.name_edit:first-child {
				margin-top: 0;
			}

			.name_edit {
				margin-top: 48rpx;
				font-size: 28rpx;
				font-family: PingFang SC-Regular, PingFang SC;
				font-weight: 400;
				line-height: 33rpx;
				display: flex;
				justify-content: space-between;

				.name {
					color: #475569;
				}

				.word_num {
					font-size: 30rpx;
					font-weight: 600;
					color: #1E293B;
				}
			}
		}



		.footer {
			width: 750rpx;
			display: flex;
			flex-direction: column;
			padding: 0 32rpx;
			position: fixed;
			left: 0;
			bottom: env(safe-area-inset-bottom);
			z-index: 10;

			.allknow {
				display: flex;
				align-items: center;
				width: 710rpx;
				height: 40rpx;
				padding: 0 32rpx;
				margin: 10rpx auto;

				.isknow {
					font-size: 28rpx;
					font-family: PingFang SC-Regular, PingFang SC;
					font-weight: 400;
					color: #666666;
					margin-left: 8rpx;

					text {
						color: #4175EE;
					}
				}
			}

			.btn {
				text-align: center;
				width: 686rpx;
				height: 86rpx;
				line-height: 86rpx;
				font-size: 32rpx;
				font-family: PingFang SC-Medium, PingFang SC;
				font-weight: 500;
				color: #FFFFFF;
				background: #4175EE;
				border-radius: 64rpx;
				margin: 20rpx auto;
			}

			.bg {
				width: 688rpx;
				height: 88rpx;
				background: #8ABAFF;
				line-height: 88rpx;
				font-size: 32rpx;
				text-align: center;
				font-family: PingFang SC-Medium, PingFang SC;
				font-weight: 400;
				color: #FFFFFF;
				border-radius: 64rpx;
			}

			.gh_ {
				margin-bottom: 30rpx;
				font-size: 28rpx;
				font-family: PingFang SC-Regular, PingFang SC;
				font-weight: 400;
				color: #333333;
			}
		}

		.agreen {
			padding: 60rpx 50rpx 20rpx;
		}
	}
</style>