<template>
	<view class="container safe-area-inset-bottom">
		<MessageNotification />
		<!-- 搜索医生 -->
		<view class="search">
			<u-search placeholder="请输入关键字" bg-color="#F5f5f5" color="#999" border-color="#F5f5f5" :show-action="false"
				maxlength="21" height="66" :clearabled="true" shape="round" v-model="keyword" @blur="toSearch"
				@search="toSearch">
			</u-search>
		</view>

		<!-- 下拉菜单 -->
		<view class="drop_down">
			<d-dropdown ref="uDropdown" :close-on-click-mask="dropdownMask" transfer @open="open" @close="close"
				menu-icon="arrow-down-fill" menu-icon-size="15rpx">
				<u-dropdown-item :title="titles"></u-dropdown-item>
				<u-dropdown-item v-model="value1" title="排序" :options="options2" @change="change"></u-dropdown-item>
				<u-dropdown-item title="筛选">
					<view class="slot-content">
						<view class="u-text-center u-content-color u-m-t-20 u-m-b-20">
							<view class="content_title">
								医生职称
							</view>
							<view class="content_btn">
								<text :class="text_choose==1?'text_choose':''" @click="chooseTexts(1)">主任医师</text>
								<text :class="text_choose==2?'text_choose':''" @click="chooseTexts(2)">副主任医师</text>
								<text :class="text_choose==3?'text_choose':''" @click="chooseTexts(3)">主治医师</text>
							</view>
						</view>
						<view class="bottom_btn">
							<view class="bottom_btn_first">
								<!-- <u-button :hair-line='false' :plain="true">重置</u-button> -->
								<text @click="chooseNone">重置</text>
							</view>
							<u-button type="primary" @click="closeDropdown" class="bottom_btn_last">确定</u-button>
						</view>
					</view>
				</u-dropdown-item>
			</d-dropdown>

		</view>

		<!-- 选择坐诊医生 -->
		<view class="doctor_list">选择坐诊医生</view>
		<!-- 列表 -->
		<view class="list" v-for="(item,index) in doctorList" :key="item.id" @click="goLookDoctor(item.id)">
			<!-- 图片部分 -->
			<view class="list_info">
				<view class="list_left">
					<image :src="item.avatar || '/static/mine/avatar_1.png'" mode="医生头像"></image>
					<!-- 医生 -->
					<view class="list_title">
						<view class="titles_name">
							<text class="doctor_name">{{item.name}}</text>
							<text class="doctors">{{item.title}}</text>
						</view>
						<!-- 职称 -->
						<view class="list_yard">
							{{item.store}} &nbsp; {{item.depart}}
						</view>
					</view>
				</view>

				<view class="list_right">{{ typeMap[type] }}</view>
			</view>
			<!-- 文字部分 -->
			<view class="card">
				<!-- 擅长 -->
				<view class="list_going">
					擅长：{{item.good_at}}
				</view>

				<!-- 接诊率 -->
				<view class="list_nums">
					<view class="txt">问诊量 <text>{{item.inquiry_num }}</text></view>
					<view class="txt">接诊率 <text>{{item.accept_percent}}</text></view>
					<view class="txt">综合评分 <text>{{item.overall_score}}</text></view>
				</view>
			</view>
		</view>


		<!-- 浮层 -->
		<view class="floor" v-if="show">
			<u-popup v-model="show" mode="bottom" :mask="false">
				<view class="contents">
					<view class="confrim-btn">
						<text class="left"></text>
						<view class="right">
							<text class="title">选择科室</text>
							<text class="btn" @click="onclosed">取消</text>
						</view>
					</view>

					<!-- 左右 -->
					<view class="contents_scroll">
						<scroll-view scroll-y="true" @touchmove.stop>
							<view class="contents_scroll_left">
								<view class="box" :class="{active:actived==index}" @click="changeStyle(index)"
									v-for="(item,index) in officeList" :key="item.id">
									{{item.name}}
								</view>
							</view>
						</scroll-view>
						<view class="contents_scroll_right">
							<view v-for="(item,index) in officeList" :key="item.id">
								<scroll-view scroll-y="true" @touchmove.stop v-if="index==actived">
									<view class="lists" v-for="(item1,index) in item.child" :key="item1.id"
										@click="getDepart(item1.id,item1.name)">
										{{item1.name}}
										<text class="iconfont icon-jiantou1"></text>
									</view>
								</scroll-view>
							</view>
						</view>
					</view>
				</view>
			</u-popup>
		</view>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
	import {
		doctorList,
		getOfficeList
	} from '../../request/api/api.js'
	import {
		dDropdown
	} from '@/components/d-dropdown/d-dropdown'
	import { isGuestMode } from '@/common/utils/auth.js'
	export default {
		components: {
			dDropdown
		},
		data() {
			return {
				typeMap: {
          0: '挂号',
          1: '咨询',
          2: '复诊',
          3: '购药',
        },
				dropdownMask: true,
				show: false,
				keyword: "",
				value1: 1,
				value2: 2,
				options2: [{
						label: '综合排序',
						value: 1,
					},
					{
						label: '问诊量',
						value: 2,
					},
					{
						label: '患者评价',
						value: 3,
					}
				],
				actived: 0, // 样式
				doctorList: [], // 医生列表
				text_choosed: "",
				text_choose: "",
				doctorID: "", // 医生id
				officeList: {}, // 科室
				depart_id: "", // 科室id
				sort: "", // 排序
				titles: "科室",
				type: "",
			}
		},
		async onLoad(e) {
			this.type = e.type
			// console.log(e, 'idd');
			
			// 当 type === 2 (诊所在线问诊) 时，直接获取委托诊所和医生信息并跳转到挂号页面
			if (this.type === '2') {
				try {
					const storeId = uni.getStorageSync('store_id') || '11001';
					const { getClinicOnlineConsultationInfoApi } = await import('@/request/api/product');
					const configRes = await getClinicOnlineConsultationInfoApi({ store_id: storeId });
					
					if (configRes.data?.code === 0 || configRes.data?.code === '0') {
						const result = configRes.data?.result;
						
						if (result?.can_use && result?.delegate_doctor_id) {
							// 直接跳转到就诊人选择页面，传递医生ID和挂号类型
							uni.redirectTo({
								url: `/subPackages/doctor/doctor-userinfo?id=${result.delegate_doctor_id}&r_type=2&delegate_store_id=${result.delegate_store_id || storeId}`
							});
							return;
						} else {
							uni.showToast({
								title: result?.message || '该门店暂不支持在线问诊功能',
								icon: 'none',
								duration: 2000
							});
							// 返回上一页
							setTimeout(() => {
								uni.navigateBack();
							}, 2000);
							return;
						}
					} else {
						uni.showToast({
							title: configRes.data?.message || '获取在线问诊信息失败',
							icon: 'none',
							duration: 2000
						});
						// 返回上一页
						setTimeout(() => {
							uni.navigateBack();
						}, 2000);
						return;
					}
				} catch (error) {
					console.error('获取在线问诊信息失败:', error);
					uni.showToast({
						title: '获取在线问诊信息失败',
						icon: 'none',
						duration: 2000
					});
					// 返回上一页
					setTimeout(() => {
						uni.navigateBack();
					}, 2000);
					return;
				}
			}
		},
		methods: {
			closeDropdown() {
				this.$refs.uDropdown.close();
				this.getList()
			},
			open(index) {
				// 展开某个下来菜单时，先关闭原来的其他菜单的高亮
				// 同时内部会自动给当前展开项进行高亮
				// this.$refs.uDropdown.highlight();
				if (index == 0) {
					this.show = true
				}
			},
			close(index) {
				// 关闭的时候，给当前项加上高亮
				// 当然，您也可以通过监听dropdown-item的@change事件进行处理
				this.$refs.uDropdown.highlight(index);
			},
			onclosed() {
				// console.log(1);
				this.show = false
				this.$refs.uDropdown.close();
				this.depart_id = 0
			},
			/*切换需要*/
			changeStyle(index) {
				this.actived = index
			},
			// 排序
			change(e) {
				// console.log(e,'options2');
				this.sort = e
				this.getList()
			},
			// 筛选
			chooseNone() {
				this.text_choose = ""
				this.getList();
			},
			chooseTexts(e) {
				this.text_choose = e
			},
			getSearch(e, val) {
				this.depart_id = e
				this.titles = val
				this.getList()
			},
			getDepart(e, names) {
				// console.log(names,'depart_id');
				this.depart_id = e
				this.titles = names
				this.getList()

				setTimeout(() => {
					this.show = false
					this.$refs.uDropdown.close();
				}, 100)
			},
			// 医生id
			goLookDoctor(id) {
        // type=3 (在线复诊) 跳转医生详情页走挂号流程
        if (this.type === '3') {
          return uni.navigateTo({
            url: '/subPackages/doctor/doctor-detail?id=' + id + '&r_type=3'
          })
        }
        // type=2 保持原有逻辑
        if (this.type === '2') {
          return uni.navigateTo({
            url: '/subPackages/product/product?doctor_id=' + id + '&register_type=2'
          })
        }
        // 默认跳转医生详情
				uni.navigateTo({
					url: '/subPackages/doctor/doctor-detail?id=' + id
				})
			},

      goProduct() {
        uni.navigateTo({
          url: '/subPackages/product/product?id=' + id
        })
      },

			// 医生列表
			getList() {
				doctorList({
					method: "post",
					data: {
						store_id: uni.getStorageSync('store_id') || '11001',
						keyword: this.keyword,
						title_id: this.text_choose,
						sort: this.sort,
						depart_id: this.depart_id,
					}
				}).then((res) => {
					// console.log(res, 'res');
					// 使用 guest_mode 判断 + code/errcode 双重保险
					const isGuest = isGuestMode();
					const isNewFormat = isGuest && (res.data.code === 0 || res.data.code === '0');
					const isOldFormat = !isGuest && (res.data.errcode === 0 || res.data.errcode === '0');
					
					if (isNewFormat || isOldFormat) {
						// 新接口格式：从 result 取值
						// 老接口格式：从 data 取值
						const responseData = isGuest && res.data.result ? res.data.result : res.data.data;
						this.doctorList = responseData.list || []
					}
				})
			},

			// 科室列表
			getOfflist() {
				getOfficeList({
					method: "post",
					data: {
						store_id: uni.getStorageSync('store_id') || '11001',
					}
				}).then((res) => {
					// console.log(res, 'ks');
					// 使用 guest_mode 判断 + code/errcode 双重保险
					const isGuest = isGuestMode();
					const isNewFormat = isGuest && (res.data.code === 0 || res.data.code === '0');
					const isOldFormat = !isGuest && (res.data.errcode === 0 || res.data.errcode === '0');
					
					if (isNewFormat || isOldFormat) {
						// 新接口格式：从 result 取值
						// 老接口格式：从 data 取值
						const responseData = isGuest && res.data.result ? res.data.result : res.data.data;
						this.officeList = responseData || [];
					} else if (res.data.errcode != 0) {
						// uni.showToast({
						// 	title: res.data.msg,
						// 	duration: 1500,
						// 	mask: false,
						// 	icon: "error"
						// })

						this.$refs.uToast.show({
							title: res.data.msg,
							type: 'default',
							icon: false
						})
					}
				})
			},

			// 搜索
			toSearch() {
				this.getList()
			},
		},
		mounted() {
			this.getList();
			this.getOfflist();
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		max-height: 100%;
		width: 100vw;
		min-height: 100vh;
		padding-bottom: env(safe-area-inset-bottom);


		.search {
			width: 686rpx;
			height: 98rpx;
			margin: 0 auto;
			padding: 16rpx 0;

			.u-search {
				width: 686rpx;
				height: 66rpx;
				margin: 0 auto;
			}
		}


		.drop_down {
			background-color: #fff;
			border-bottom: 2rpx solid #F1F5F9;
			position: -webkit-sticky;
			position: sticky;
			top: var(--window-top);
			z-index: 99;

			.u-dropdown-item {
				.slot-content {
					width: 750rpx;
					padding: 1rpx 0 0rpx 1rpx;
					background-color: #fff;
					z-index: 20;

					.u-text-center {
						display: flex;
						flex-direction: column;
						padding: 10rpx 20rpx;
						text-align: left;

						.content_title {
							width: 112rpx;
							height: 40rpx;
							font-size: 28rpx;
							font-family: PingFang SC-Regular, PingFang SC;
							font-weight: 400;
							color: #1E293B;
							line-height: 33rpx;
							margin-left: 32rpx;
						}

						.content_btn {
							height: 120rpx;
							display: flex;
							align-items: center;

							text {
								width: 160rpx;
								height: 56rpx;
								text-align: center;
								line-height: 56rpx;
								background: #F7F8FA;
								border-radius: 64rpx;
								margin: 0 20rpx 0 22rpx;
							}

							.text_choose {
								width: 160rpx;
								height: 56rpx;
								text-align: center;
								line-height: 56rpx;
								border-radius: 64rpx;
								margin: 0 20rpx 0 22rpx;
								background: rgba(83, 109, 254, 0.1);
								color: #4175EE;
							}
						}
					}

					.bottom_btn {
						width: 740rpx;
						height: 86rpx;
						display: flex;
						margin: 0 auto 10rpx;
						justify-content: space-around;
						align-items: center;

						.bottom_btn_first {
							width: 375rpx;
							height: 86rpx;
							display: flex;
							justify-content: space-around;
							align-items: center;
							background: #fff;
							color: #4175EE;
							border-radius: 0;
							border: 1rpx solid #4175EE;
						}

						.bottom_btn_last {
							width: 375rpx;
							height: 86rpx;
							line-height: 86rpx;
							text-align: center;
							background: #4175EE;
							color: #fff;
							border-radius: 0;
							border: 1rpx solid #4175EE;
						}
					}

				}

			}
		}

		.doctor_list {
			width: 670rpx;
			font-size: 32rpx;
			font-family: PingFang SC-Bold, PingFang SC;
			font-weight: bold;
			color: #232323;
			margin: 30rpx auto 34rpx;
		}

		.list {
			width: 710rpx;
			background: linear-gradient(180deg, #E2F1FF 0%, #FBFDFF 24%, #FFFFFF 100%);
			margin: 32rpx auto 52rpx;
			border-radius: 16rpx;
			padding: 22rpx 32rpx;
			margin: 32rpx auto 52rpx;
			box-shadow: 0px 0px 18px 0px rgba(0, 0, 0, 0.08);

			.list_info {
				display: flex;
				justify-content: space-between;

				.list_left {
					height: 96rpx;
					display: flex;
					align-items: center;
					justify-content: space-around;

					image {
						width: 96rpx;
						height: 96rpx;
						border-radius: 50%;
						margin: 0 16rpx 0 0;
						vertical-align: middle;
					}

					.list_title {
						display: flex;
						flex-direction: column;

						.titles_name {
							margin: 16rpx 0;

							.doctor_name {
								height: 40rpx;
								font-size: 32rpx;
								font-family: PingFang SC-Bold, PingFang SC;
								font-weight: bold;
								color: #232323;
								line-height: 40rpx;
								margin-right: 16rpx;
							}

							.doctors {
								height: 40rpx;
								font-size: 20rpx;
								font-family: PingFang SC-Regular, PingFang SC;
								font-weight: 400;
								color: #333333;
								line-height: 30rpx;
							}
						}

						.list_yard {
							font-size: 24rpx;
							font-family: PingFang SC-Regular, PingFang SC;
							font-weight: 400;
							color: #666666;
						}
					}
				}

				.list_right {
					width: 104rpx;
					height: 50rpx;
					line-height: 50rpx;
					text-align: center;
					background: #4175EE;
					border-radius: 26rpx 26rpx 26rpx 26rpx;
					font-size: 24rpx;
					font-family: PingFang SC-Bold, PingFang SC;
					font-weight: bold;
					color: #FFFFFF;

				}
			}

			.card {

				.list_nums {
					height: 34rpx;
					font-size: 28rpx;
					font-family: PingFang SC-Regular, PingFang SC;
					font-weight: 500;
					color: #666666;
					margin: 18rpx 0 24rpx;
					display: flex;
					align-items: center;

					.txt {
						margin-right: 30rpx;

						text {
							font-size: 28rpx;
							color: #FEA54C;
							margin: 0 10rpx;
						}
					}
				}

				.list_going {
					font-size: 24rpx;
					font-family: PingFang SC-Regular, PingFang SC;
					font-weight: 400;
					color: #232323;
					line-height: 44rpx;
					display: -webkit-box;
					-webkit-line-clamp: 2;
					-webkit-box-orient: vertical;
					text-overflow: ellipsis;
					overflow: hidden;
					margin: 16rpx auto;
				}

				.list_price {
					display: flex;
					align-items: center;

					.picture {
						width: 140rpx;
						height: 60rpx;
						line-height: 58rpx;
						text-align: center;
						border-radius: 4rpx 4rpx 4rpx 4rpx;
						border: 2rpx solid #4175EE;
						font-size: 24rpx;
						font-family: PingFang SC-Bold, PingFang SC;
						font-weight: bold;
						color: #4175EE;
						margin: 0 30rpx 0 0;
					}
				}
			}
		}

		.floor {
			width: 100vw;
			height: 100vh;

			.contents {
				width: 100vw;
				height: 100vh;

				.confrim-btn {
					width: 100%;
					height: 9%;
					display: flex;
					justify-content: flex-end;
					align-items: center;

					.right {
						width: 486rpx;
						display: flex;
						align-items: center;
						justify-content: space-between;

						.title {
							width: 144rpx;
							height: 50rpx;
							font-size: 36rpx;
							font-family: PingFang SC-Regular, PingFang SC;
							font-weight: 400;
							color: #0F172A;
						}

						.btn {
							width: 82rpx;
							height: 42rpx;
							font-size: 34rpx;
							border: 0;
							background-color: #fff;
							color: #969799;
						}
					}


				}

				.contents_scroll {
					width: 100%;
					height: 91%;
					display: flex;

					.contents_scroll_left {
						width: 264rpx;
						background: #F8FAFC;
						text-align: center;

						.box {
							width: 264rpx;
							background: #F8FAFC;
							line-height: 104rpx;
							font-size: 30rpx;
							font-family: PingFang SC-Semibold, PingFang SC;
							font-weight: 600;
							color: #475569;
						}


						.active {
							background: #FFFFFF;
							color: #4175EE;
						}
					}

					.contents_scroll_right {
						width: 486rpx;
						background-color: #fff;

						.lists {
							width: 486rpx;
							height: 104rpx;
							padding: 32rpx 0 32rpx 40rpx;
							font-size: 28rpx;
							font-family: PingFang SC-Regular, PingFang SC;
							font-weight: 400;
							color: #1E293B;
							display: flex;
							align-items: center;
							justify-content: space-between;
							padding: 0 54rpx 0 74rpx;
						}
					}
				}
			}
		}
	}
</style>