<template>
	<!-- 医院以及就诊人弹窗公共组件 -->
	<view :class="hospVisible ? 'hosp-pat-select' : ''">
		<van-overlay :show="hospVisible" @click.stop="hideHospVisible"></van-overlay>
		<view v-if="hospVisible" class="hosp-modal">
			<view class="hosp-header">{{ hospVal ? "切换医院" : "选择医院" }}
				<view class="hosp-header-icon">
					<van-icon v-if="hospVal ? true : false" name="cross" @click="hideHospVisible" />
				</view>
			</view>
			<scroll-view scroll-y="true" class="hosp-content">
				<radio-group>
					<van-cell-group>
						<van-cell v-for="(item, index) in allHospData" :key="index" :title="item.hospDesc" titleWidth="360rpx" clickable :dataName="item.hospID" @click="hospVanCellOnClick">
							<template v-slot:right-icon>
								<radio class="radio-blue" :name="item.hospID" :checked="hospVal == item.hospID" />
							</template>
						</van-cell>
					</van-cell-group>
				</radio-group>
			</scroll-view>
			<view class="hosp-footer border-top-before" @tap.stop="handleConfirm">确认</view>
		</view>
		<van-action-sheet :show="patVisible" :closeable="false">
			<view class="choose-pat-picker">
				<view class="picker-head">
					<view class="cancel" @tap="handlePatCancel">取消</view>
					<view class="picker-head-title">选择就诊人</view>
					<view class="confirm" @tap="handlePatConfirm">确定</view>
				</view>
				<picker-view class="picker-view" indicator-style="height: 50px;line-height: 50px" :value="[patValue]"
					@change="handlePatChange">
					<picker-view-column>
						<view class="picker-view-item" v-for="(item, index) in admSelectData" :key="index">{{ item.patName
						}}</view>
					</picker-view-column>
				</picker-view>
			</view>
		</van-action-sheet>
	</view>
</template>

<script>
	import $http from '@/utils/https.js';
	import Utils from '@/utils/utils.js';
	import { getHospList, switchHospital, dealSwitchHospital } from '@/utils/common.js';
	import globalMixin from '@/mixins/globalMixin';
	import VanIcon from '../icon/index.vue'
	import VanPopup from '../popup/index.vue'
	import VanOverlay from '../overlay/index.vue'
	import VanActionSheet from '../action-sheet/index.vue'
	import VanCellGroup from '../cell-group/index.vue'
	import VanCell from '../cell/index.vue'
	const app = getApp()
	export default {
		mixins: [globalMixin],
		components: {
			'van-icon': VanIcon,
			'van-popup': VanPopup,
			'van-overlay': VanOverlay,
			'van-action-sheet': VanActionSheet,
			'van-cell-group': VanCellGroup,
			'van-cell': VanCell
		},
		data() {
			return {
				userData: {},
				hospVisible: false,
				hospVal: "",
				patVisible: false,
				patValue: 0,
				patCacheValue: null,
				allHospData: [],
				currentHospData: {}, // 当前医院数据
				admSelectData: [],
				originalData: null,
				curentLatLong: '',
				province: '',
				isPosition: false, // 定位是否成功
			}
		},
		onReady() {
			console.log('HospSelect组件 onReady')
			// this._init()
		},
		methods: {
			// 获取userData
			_init() {
				return new Promise((resolve, reject) => {
					const userData = this.$cache.get('userData');
					const allHospitalData = this.$cache.get('allHospitalData');
					// console.log('获取医院列表数据完成 hospPatSelect====', allHospitalData)
					this.setData({
						userData: userData
					}, async () => {
						if (this.province) {
							this.setData({
								isPosition: true
							})
						} 
						if(allHospitalData) {
							// 切换到相应医院
							this.onSwitchHosp(allHospitalData).then(() => {
								this.userScanTouchFun() // 活动海报用户扫描进入
							})
						}
					})
				})
			},

			// 获取医院数据
			getHospSelectData: function() {
				const _this = this
				return new Promise(async (resolve, reject) => {
					let {
						userData
					} = _this;

					// console.log("医院数据", this.count)
					if (!(userData && userData.openID)) {
						this.count = this.count ? this.count : 1;
						if (this.count > 10) {
							return;
						}
						setTimeout(() => {
							this._init();
						}, 300)
						this.count++;
						return;
					}
					uni.showLoading()
					await getHospList(app)
						.then(data => {
							uni.hideLoading()
							console.log('获取医院列表数据完成 hospPatSelect', data)
							if(data) { // 如果只有一家医院，获取到该医院数据，设置医院病刷新数据，再获取就诊人数据
								_this.setPubUserData(data)
							}
							const allHospData = res.result
							_this.setData({
								allHospData
							}, () => {
								const userData = this.$cache.get('userData')
								if (!(userData && userData.hospID)) { // 如果userData中没有医院信息，弹窗提示选择医院
									_this.showHospVisible()
								}
							})
						})
						.catch(error => {})
				})
			},
			
			setPubUserData(hospOneData) {
				const _this = this
				_this.setData({
					hospVal: hospOneData.hospID || ""
				}, () => {
					// 重新初始化数据，刷新首页标题栏医院数据
					_this.$emit('handleReRender', {
						type: 'selectHosp'
					});
					setTimeout(() => {
						hospOneData.hospID && _this.getAdmSelectData();
					}, 300)
				})
			},

			// 获取就诊人下拉数据
			getAdmSelectData: function() {
				let data = {
					params: [{}]
				}
				$http.post("urlS", this, {
					code: "01030001",
					data: data,
					success: function(res) {
						if (+res.errorCode === 0) {
							app.globalData.isUpdatePatList = false;
							let admSelectData = res.result.rows && res.result.rows.length > 0 ? res.result.rows : [];
							for (var i = 0; i < admSelectData.length; i++) {
								admSelectData[i].value = admSelectData[i].patID;
								admSelectData[i].key = i;
							}
							this.setData({
								admSelectData: admSelectData
							}, () => {
								this.judgeWhetherThePatientExists();
							});
						} else {
							this.setData({
								admSelectData: []
							}, () => {
								uni.showToast({
									icon: 'none',
									content: res.errorMessage
								});
								this.judgeWhetherThePatientExists();
							});
						}
					}
				});
			},
			
			// 活动海报用户扫描进入 touch
			userScanTouchFun() {
			    let recommendObj = app.globalData.activityObj
			    if(!app.globalData.activityObj) {
			        recommendObj = this.$cache.get('recommendObj')
			    }
			    if(recommendObj && (!recommendObj.timeMap || (recommendObj.timeMap && recommendObj.timeMap > new Date().getTime()))) {
			        console.log('首页 userScanTouch', recommendObj)
			        userScanTouch(recommendObj) // 活动海报用户扫描进入
			    }
			},
				
			/**
			 * 1、如果只有一家医院，默认选中该医院
			 * 2、如果是活动直接扫码进入，直接切换到该医院
			 */
			onSwitchHosp(allHospData) {
				return new Promise((resolve, reject) => {
					const {
						isPosition
					} = this
					let isChooseHosp = false
					let currentHospData = {}
					// 当活动传入参数时，自动切换医院
					dealSwitchHospital(allHospData, app, app.globalData?.activityObj?.hspcode).then(data => {
						if(data) {
							isChooseHosp = true
						} else {
							currentHospData = data
						}
					})
					this.setData({
						userData: this.$cache.get('userData')
					})
					// 如果没有选中的医院，则停止执行后续代码
					if (!isChooseHosp) {
						return
					} else {
						this.setData({
							currentHospData,
							hospVal: currentHospData.hospID || ""
						}, () => {
							setTimeout(() => {
								this.getAdmSelectData();
							}, 300)
						})
					}
					resolve()
				})
			},

			// 判断就诊人数据中是否包含storage中选中的数据，如果不包含则清空storage就诊人数据
			judgeWhetherThePatientExists: function() {
				let {
					allHospData,
					admSelectData
				} = this;
				let userData = this.$cache.get('userData');
				let isExistence = false;
				let newData = {};
				for (var i = 0; i < admSelectData.length; i++) {
					if (userData && userData.patID && (admSelectData[i].patID === userData.patID)) {
						isExistence = true;
						newData = admSelectData[i];
						break
					}
				}
				if (!isExistence) {
					this.$cache.set('userData', {
						...userData,
						idCardNo: '',
						imUserID: '',
						patDesc: '',
						patID: '',
						hisPatNo: '',
						hisPatID: '',
						mobile: '',
						patValue: '',
						patSexDesc: '',
						medCardID: ''
					})
				} else {
					this.$cache.set('userData', {
						...userData,
						idCardNo: newData.idCardNo || '',
						imUserID: newData.imUserID || '',
						patDesc: newData.patName || '',
						patID: newData.patID || '',
						hisPatNo: newData.hisPatNo || '',
						hisPatID: newData.hisPatID || '',
						mobile: newData.mobile || '',
						patValue: newData.key || '',
						patSexDesc: newData.patSexDesc || '',
						medCardID: newData.medCardID || ''
					});
				}
				// console.log("触发了this.$emit,刷新首页数据")
				this.$emit('upDateAdmData', {
					type: '',
					patDataLen: admSelectData ? admSelectData.length : 0,
				});
			},

			// 打开就诊人选择弹窗
			handleShowPatModal: function() {
				console.log('handleShowPatModal 执行了')
				let userData = this.$cache.get('userData')
				this.setData({
					patVisible: true,
					patValue: userData.patValue || 0,
					patCacheValue: userData.patValue || 0
				}, () => {
					console.log('patVisible:' + this.patVisible)
				})
			},
			
			// 选择就诊人
			handlePatChange(event) {
				const {
					value
				} = event.detail;
				this.setData({
					patCacheValue: value[0]
				})
			},

			// 关闭选择就诊人弹窗
			handlePatCancel: function() {
				this.setData({
					patVisible: false
				})
			},

			// 确认就诊人
			handlePatConfirm() {
				const {
					patCacheValue,
					admSelectData
				} = this;
				const value = admSelectData && admSelectData[patCacheValue]
				let userData = this.$cache.get('userData');
				if (!(userData && userData.imUserID)) {
					app.globalData.isLogOut = false;
				}
				this.$cache.set('userData', {
					...userData,
					idCardNo: value.idCardNo,
					imUserID: value.imUserID,
					patDesc: value.patName,
					patID: value.patID,
					hisPatNo: value.hisPatNo,
					hisPatID: value.hisPatID,
					mobile: value.mobile,
					patValue: value.key,
					patSexDesc: value.patSexDesc,
					medCardID: value.medCardID
				});
				this.setData({
					patValue: value.key
				})
				this.handlePatCancel();
				this.$emit('handleReRender', {
					type: 'selectAdm'
				});
			},
		
			// 打开医院弹窗
			showHospVisible: function() {
				console.log('打开医院选择弹窗')
				this.setData({
					hospVisible: true
				}, () => {
					console.log('hospVisible', this.hospVisible)
				})
			},
			
			// 关闭医院弹窗
			hideHospVisible: function() {
				let userData = this.$cache.get('userData');
				if (userData && userData.hospID) {
					this.setData({
						hospVisible: false
					})
				} else {
					return;
				}
			},
			
			// 医院选择
			hospRadioChange: function(event) {
				console.log(event)
				this.setData({
					hospVal: event.detail
				});
			},

			// 医院选择
			hospVanCellOnClick: function(e) {
				const self = this
				return new Promise((resolve, reject) => {
					const {
						name
					} = e.currentTarget.dataset;
					self.setData({
						hospVal: name
					}, () => {
						resolve()
					});
				})
			},
			
			// 确认医院
			handleConfirm: function() {
				let {
					allHospData,
					hospVal
				} = this;
				let userData = this.$cache.get('userData')
				if (!hospVal) {
					uni.showToast({
						icon: 'none',
						content: '请选择医院!'
					})
				}
				for (var i = 0; i < allHospData.length; i++) {
					if (allHospData[i].hospID === hospVal) {
						this.$cache.set('userData', {
							...userData,
							hospID: allHospData[i].hospID,
							hospDesc: allHospData[i].hospDesc,
							hisHospID: allHospData[i].hisHospID,
							hospAddress: allHospData[i].hospAddress,
							telephone: allHospData[i].telephone,
							menuMode: allHospData[i].menuMode,
							serviceCallTips: allHospData[i].serviceCallTips,
							serviceCall: allHospData[i].serviceCall,
							upLoadUrl: allHospData[i].upLoadUrl,
							downLoadUrl: allHospData[i].downLoadUrl,
							// 医保相关字段
							insuType: allHospData[i].insuType,
							bizType: allHospData[i].bizType,
							cityCode: allHospData[i].cityCode,
							channel: allHospData[i].channel,
							orgChnlCrtfCodg: allHospData[i].orgChnlCrtfCodg,
							orgCodg: allHospData[i].orgCodg,
							orgAppId: allHospData[i].orgAppId,
							sourceapp: allHospData[i].sourceapp,
							insuTestFlag: allHospData[i].insuTestFlag,
						})
						app.globalData.SDKAPPID = +allHospData[i].imAppID;
						app.globalData.SECRETKEY = allHospData[i].imSecret;
						break
					}
				}
				userData && userData.HospID && this.getAdmSelectData(); // 获取就诊人下拉数据
				this.hideHospVisible(); // 关闭了医院选择弹窗
				this.$emit('handleReRender', {
					type: 'selectHosp'
				});
			}
		}
	}
</script>

<style lang="scss">
	.wrapper {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100%;
	}

	.hosp {
		&-pat-select {
			position: fixed;
			left: 0;
			top: 0;
			bottom: 0;
			right: 0;
			z-index: 10;
		}

		&-modal {
			position: fixed;
			z-index: 999;
			left: 50%;
			top: 50%;
			width: 540rpx;
			height: 648rpx;
			overflow: hidden;
			background-color: #fff;
			border-radius: 20rpx;
			transform: translate(-50%, -50%);
		}

		&-header {
			position: relative;
			height: 108rpx;
			line-height: 108rpx;
			width: 100%;
			text-align: center;
			font-size: 36rpx;
			color: #000;
			position: relative;
			padding: 0 48rpx;
			box-sizing: border-box;
		}

		&-header-icon {
			position: absolute;
			top: 50%;
			right: 48rpx;
			font-size: 40rpx;
			color: #999;
			transform: translateY(-50%);
		}

		&-content {
			height: 100%;
			line-height: 100%;
			height: 440rpx;
			overflow: auto;
			padding: 0 12rpx 0 24rpx;
			box-sizing: border-box;
		}

		&-footer {
			height: 100rpx;
			line-height: 100rpx;
			width: 100%;
			text-align: center;
			font-size: 36rpx;
			color: #108ee9;
			border-top: 1rpx solid #ddd;
		}
	}

	.choose-pat-picker {
		// position: fixed;
		// left: 0;
		// bottom: 0;
		// #ifdef H5
		padding-bottom: 140rpx;
		// #endif
		width: 100%;
		height: 500rpx;
		background-color: #fff;
		box-shadow: 0 -10rpx 6rpx -6rpx rgba(0, 0, 0, 0.05);

		.picker-head {
			box-sizing: border-box;
			display: flex;
			align-items: center;
			justify-content: space-between;
			height: 100rpx;
			width: 100%;
			padding: 0 20rpx;

			.cancel,
			.confirm {
				color: #007FCC;
				font-size: 28rpx;
			}
		}

		.picker-view {
			height: 500rpx;

			&-item {
				height: 100rpx;
				line-height: 100rpx;
				text-align: center;
			}
		}
	}

	.van-cell__title {
		flex: 2;
	}
</style>